简体   繁体   English

Angular:如何在控制器中访问元素指令的作用域

[英]Angular: How to access an element directive's scope in the controller

Given this simple Angular module: 鉴于此简单的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";

    }
}
});

How do I access club and max in the controller function? 如何在控制器功能中访问club和max?

Thanks, Jeff 谢谢杰夫

Attributes on the scope set up with '@', as in scope: { myAttr: '@' } receive their values after the controller function has been called. 设置为@的范围内的属性(如scope: { myAttr: '@' }在调用控制器函数会接收其值。

You can demonstrate this with a simple setTimeout - See http://jsfiddle.net/Q4seC/ (be sure to open the console) 您可以通过一个简单的setTimeout演示它-请参阅http://jsfiddle.net/Q4seC/ (确保打开控制台)

$attrs, as you've found, is ready when you need it. 您已经发现,$ attrs在需要时就可以使用了。

Interestingly, if you use '=' instead of '@', the value is ready and available, which makes me think this could be considered a bug in Angular... 有趣的是,如果您使用'='而不是'@',则该值已准备就绪且可用,这使我认为这可以视为Angular中的错误...

The 2 mentioned variables ( max and club ) will be simply defined in a scope injected to directive's controller. 提到的2个变量( maxclub )将在注入指令的控制器的范围内简单定义。 This means that you can write: 这意味着您可以编写:

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;
        });
}

in your directive's controller. 在指令的控制器中。

If you want to read up more I would suggest the "Directive Definition Object" in the http://docs.angularjs.org/guide/directive where it talks about scopes in directives. 如果您想阅读更多内容,我会在http://docs.angularjs.org/guide/directive中建议“指令定义对象”,其中讨论了指令的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM