指令是Angular1.X中比较复杂的内容,自定义指令能实现许多操作DOM元素的功能。下面就介绍七个简单场景下的自定义指令。
1.模拟ng-bind-html指令
思路:可以自定义一个属性指令(A),属性指令的值即需要替换的html文本,利用指令的link可以给带有该指令的元素添加经过$compile编译后($compile(XXX)(scope))的html文本。
结果截图:
代码:
<!doctype html>
<html ng-app="MyApp">
<head>
<meta charset="UTF-8">
<title>指令实现ng-bind-html</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/angular.js/1.3.0/angular.min.js"></script>
</head>
<body>
<!-- 实现:手动模拟ng-bind-html指令 -->
<!-- 利用link及compile -->
<div ng-controller="myCtrl" bind-html="string">
</div>
</body>
<script>
var myApp = angular.module('MyApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.string = '<button type="button" class="btn btn-primary" ng-click="btnFunc()">测试html按钮</button>';
});
myApp.directive('bindHtml', function($compile) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
if (scope.string) {
scope.$watch(attrs.bindHtml, function() {
/* 注意此处需要编译后的html代码,否则只会添加文本,无法添加绑定的事件 */
elem.append($compile(scope.string)(scope));
});
/* 添加的点击事件 */
scope.btnFunc = function() {
console.log('121');
};
}
}
};
});
</script>
</html>
注:append的代码需要编译后的html代码,否则只会添加文本,无法添加绑定的事件!并且在此处使用innerHTML也不会
2.给指令绑定不同的鼠标悬浮事件
场景描述:两行“数据加载中…”有不同的悬浮事件
思路:可以自定义一个指令,包含点击事件的属性,在子控制器中定义点击事件。
结果截图:
代码:
<!doctype html>
<html ng-app="MyApp">
<head>
<meta charset="UTF-8">
<title>Directive</title>
<script src="https://cdn.bootcss.com/angular.js/1.3.0/angular.min.js"></script>
</head>
<body>
<!-- 实现:给指令绑定不同的鼠标悬浮事件 -->
<!-- 相同指令在其自己的controller中,可以通过设置属性值(attr)传递不同的函数然后绑定到指令元素上 -->
<div ng-controller="MyCtrl1">
<loader howToLoad="loadFunc1()">数据加载中...</loader>
</div>
<div ng-controller="MyCtrl2">
<loader howToLoad="loadFunc2()">数据加载中...</loader>
</div>
<script type="text/javascript">
var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl1', ['$scope', function($scope) {
$scope.loadFunc1 = function() {
console.log('加载数据1...');
};
}]);
myApp.controller('MyCtrl2', ['$scope', function($scope) {
$scope.loadFunc2 = function() {
console.log('加载数据2...');
}
}]);
myApp.directive('loader', function() {
return {
restrict: "AE",