我正在学习 Angular directive
我无法理解 scope
话题。假设我有这个自定义directive
其名称为parentDirective
。它有一个controller
属性(property)和link
属性,如下:
angular.module("app").directive("parentDirective", function () {
return {
restrict: "E",
templateUrl: "dirs/parent.html",
scope:{
character: "="
},
controller: function ($scope) {
$scope.getData = function (data) {
console.log(data);
}
},
link: function (scope,elem, attrs) {
elem.bind("click", function (e) {
//get object here?
});
scope.getData = function (data) {
console.log(data);
}
}
}
});
其模板定义如下:
<p ng-click="getData(character)">
{{character.name}}
</p>
我可以获得character
controller
中的对象通过$scope
功能变量和我可以访问 link
中的相同数据功能通过scope
。这两种方法在这方面有什么区别?第二个问题,是否可以绑定(bind)click
到directive
并获取这样的对象:
elem.bind("click", function (e) {
//get object here?
});
最佳答案
作用域特定于当前指令实例,并且在两个函数中是同一对象。
对于在作用域上定义方法,如果在 Controller 或链接函数中定义它们没有区别,除非存在竞争条件要求尽早定义方法。因此,在 Controller 中定义作用域方法是有意义的。
事件处理程序与任何其他函数没有什么不同,它是
elem.on("click", function (e) {
scope.$apply(function () {
scope.character...
});
});
scope.$apply(...)
包装器无论如何都不会造成伤害,但它的必要性取决于 scope.character
发生的情况。
指令只能有controller
而没有link
。当前的 Angular 版本(1.5+)建议采用 bindToController
+ controllerAs
的样式使用而不是 scope
绑定(bind)作为指令和组件的共同基础。
那么指令可能看起来像
restrict: "E",
template: '<p>{{$ctrl.character.name}}</p>',
controllerAs: '$ctrl',
bindToController: { character: "=" },
controller: function ($element, $scope) {
var self = this;
self.getData = function (data) { ... };
$element.on("click", function (e) {
scope.$apply(function () {
self.character...
});
});
}
link
函数可能显示为 $postLink
controller hook ,但这里不需要。
关于javascript - Angular Directive(指令) : whats the difference between scope in controller vs scope in link function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41778436/