簡體   English   中英

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

[英]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個變量( maxclub )將在注入指令的控制器的范圍內簡單定義。 這意味着您可以編寫:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM