您的位置:首页 > Web前端 > AngularJS

简话Angular 06 Angular自定义指令

2015-07-21 19:24 603 查看
一句话: 直接return link函数可以解决大多数问题,无须死扣用法

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

<h3>Custom directive, with dom operation, events, css and scope model operation</h3>

<div ng-controller="DateController">
Date format: <input ng-model="format"> <hr/>
Current time is: <span my-current-time="format"></span>
</div>

<script>
var myApp = angular.module('myApp', []);

myApp.controller('DateController', function($scope) {
$scope.format = "M/d/yy h:mm:ss a";
});

myApp.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {
function link(scope, element, attrs) {
var format, timeoutId;

function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

function updateTime() {
element.text(dateFilter(new Date(), format));
element.css({'background-color': getRandomColor()});
}

scope.$watch(attrs.myCurrentTime, function(value) {
format = value;
updateTime();
});

element.on('$destroy', function() {
$interval.cancel(timeoutId);
});

element.on('click', function(){
alert('Date format is changing to yyyy/MM/dd hh');
scope.format = "yyyy/MM/dd hh " + getRandomColor();
});

// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(function() {
updateTime(); // update DOM
}, 1000);
}

return {
link: link
};
}]);
</script>
</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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: