【发布时间】:2017-01-21 10:48:09
【问题描述】:
我正在学习 Angular directives,但我无法围绕 scope 主题。假设我有这个名为parentDirective 的自定义directive。它有一个controller 属性和一个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>
我可以通过$scope 变量在controller 函数中获取character 对象,并且我可以通过scope 访问link 函数中的相同数据。这两种方法在这方面有什么区别?第二个问题,是否可以将click 绑定到directive 并获得这样的对象:
elem.bind("click", function (e) {
//get object here?
});
【问题讨论】:
-
没有区别。这是同一个对象。
标签: javascript angularjs angularjs-directive angular-directive