简话Angular 06 Angular自定义指令

一句话: 直接return link函数可以解决大多数问题,无须死扣用法

 

1. 上源码 (dom操作,事件,css,mode操作全包括了)

 1 <h3>Custom directive, with dom operation, events, css and scope model operation</h3> 
 2         
 3 
 4         <div ng-controller="DateController">
 5           Date format: <input ng-model="format"> <hr/>
 6           Current time is: <span my-current-time="format"></span>
 7         </div>
 8 
 9 
10 
11         <script>
12         var myApp = angular.module('myApp', []);
13 
14         myApp.controller('DateController', function($scope) {
15             $scope.format = "M/d/yy h:mm:ss a";
16         });
17         
18         myApp.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {
19             function link(scope, element, attrs) {
20                 var format, timeoutId;
21 
22                 function getRandomColor() {
23                     var letters = '0123456789ABCDEF'.split('');
24                     var color = '#';
25                     for (var i = 0; i < 6; i++ ) {
26                         color += letters[Math.floor(Math.random() * 16)];
27                     }
28                     return color;
29                 }
30 
31                 function updateTime() {
32                     element.text(dateFilter(new Date(), format));
33                     element.css({'background-color': getRandomColor()});
34                 }
35 
36                 scope.$watch(attrs.myCurrentTime, function(value) {
37                     format = value;
38                     updateTime();
39                 });
40 
41                 element.on('$destroy', function() {
42                     $interval.cancel(timeoutId);
43                 });
44 
45                 element.on('click', function(){
46                     alert('Date format is changing to yyyy/MM/dd hh');
47                     scope.format = "yyyy/MM/dd hh " + getRandomColor();
48                 });
49 
50                 // start the UI update process; save the timeoutId for canceling
51                 timeoutId = $interval(function() {
52                     updateTime(); // update DOM
53                 }, 1000);
54             }
55 
56             return {
57                 link: link
58             };
59         }]);
60         </script>
61     </div>

 

2. 在线查看运行效果

http://jimuyouyou.github.io/angular-bootstrap-rest-seed/examples/angular/6-custom-directive.html

 

3. 项目地址

github: https://github.com/jimuyouyou/angular-bootstrap-rest-seed

posted on 2015-07-21 19:24  码流星  阅读(194)  评论(0编辑  收藏  举报

导航