[英]Angular: How to access an element directive's scope in the controller
鉴于此简单的Angular模块:
angular.module('fixturesModule', [])
.directive('clubfixtures', function () {
"use strict";
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
club : "@club",
max : "@max"
},
templateUrl: "ClubResultsTemplate.html",
controller: function ($scope, $http) {
$http.get("data.json").success(function (data) {
$scope.results = data;
});
$scope.sortBy = "Date";
}
}
});
如何在控制器功能中访问club和max?
谢谢杰夫
设置为@的范围内的属性(如scope: { myAttr: '@' }
在调用控制器函数后会接收其值。
您可以通过一个简单的setTimeout演示它-请参阅http://jsfiddle.net/Q4seC/ (确保打开控制台)
您已经发现,$ attrs在需要时就可以使用了。
有趣的是,如果您使用'='而不是'@',则该值已准备就绪且可用,这使我认为这可以视为Angular中的错误...
提到的2个变量( max
和club
)将在注入指令的控制器的范围内简单定义。 这意味着您可以编写:
controller: function ($scope, $http) {
$scope.max; //do sth with $scope.max
$scope.club //so sth with $scope.club
$http.get("data.json").success(function (data) {
$scope.results = data;
});
}
在指令的控制器中。
如果您想阅读更多内容,我会在http://docs.angularjs.org/guide/directive中建议“指令定义对象”,其中讨论了指令的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.