标题:
Angular Directive 详解(5)
[打印本页]
作者:
look_w
时间:
2019-3-8 18:46
标题:
Angular Directive 详解(5)
我们将上面的directive简单的改一下,
myDirectives.directive('myAttr', function() {
return {
restrict: 'E',
template: 'Name: {{customerInfo.name}} Address: {{customerInfo.address}}<br>' +
'Name: {{vojta.name}} Address: {{vojta.address}}'
};
});
复制代码
运行结果如下:
Name: Address:
Name: Vojta Address: 3456 Somewhere Else
复制代码
因为此时的directive没有定义独立的scope,customerInfo是undefined,所以结果正好与上面相反。
transclude的使用
transclude的用法,有点像jquery里面的$().html()功能
myDirective.directive('myEvent', function() {
return {
restrict: 'E',
transclude: true,
scope: {
'close': '$onClick' //根html中的on-click="hideDialog()"有关联关系
},
templateUrl: '../partials/event_part.html'
};
});
myController.controller('eventTest', [
'$scope',
'$timeout',
function($scope, $timeout) {
$scope.name = 'Tobias';
$scope.hideDialog = function() {
$scope.dialogIsHidden = true;
$timeout(function() {
$scope.dialogIsHidden = false;
}, 2000);
};
}
]);
复制代码
<body ng-app="phonecatApp">
<div ng-controller="eventtest">
<my-event ng-hide="dialogIsHidden" on-click="hideDialog()">
Check out the contents, {{name}}!
</my-event>
</div>
</body>
<!--event_part.html -->
<div>
<a href ng-click="close()">×</a>
<div ng-transclude></div>
</div>
复制代码
说明:这段html最终的结构应该如下所示:
<body ng-app="phonecatApp">
<div ng-controller="eventtest">
<div ng-hide="dialogIsHidden" on-click="hideDialog()">
<span>Check out the contents, {{name}}!</span>
</div>
</div>
</body>
复制代码
将原来的html元素中的元素Check out the contents, !插入到模版的
中,还会另外附加一个标签。 controller,link,compile之间的关系
myDirective.directive('exampleDirective', function() {
return {
restrict: 'E',
template: '<p>Hello {{number}}!</p>',
controller: function($scope, $element){
$scope.number = $scope.number + "22222 ";
},
link: function(scope, el, attr) {
scope.number = scope.number + "33333 ";
},
compile: function(element, attributes) {
return {
pre: function preLink(scope, element, attributes) {
scope.number = scope.number + "44444 ";
},
post: function postLink(scope, element, attributes) {
scope.number = scope.number + "55555 ";
}
};
}
}
});
//controller.js添加
myController.controller('directive2',[
'$scope',
function($scope) {
$scope.number = '1111 ';
}
]);
//html
<body ng-app="testApp">
<div ng-controller="directive2">
<example-directive></example-directive>
</div>
</body>
复制代码
上面小例子的运行结果如下:
Hello 1111 22222 44444 5555 !
复制代码
由结果可以看出来,controller先运行,compile后运行,link不运行。 我们现在将compile属性注释掉后,得到的运行结果如下: Hello 1111 22222 33333 !
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0