1

我有一个指令。我想在我的指令控制器中使用该指令的属性值。我试图通过将属性值绑定到我的隔离范围来做到这一点。但是我遇到了一个问题,即属性值似乎没有立即绑定到隔离范围。

考虑以下代码:

angular.module('startup.directives.decision', [])

    .directive('decisionMaker', [function () {
        return{
            restrict: 'E',
            templateUrl: 'views/directives/decision.html',
            scope: {
                decisionType:"@",
            }, 
            controller: ['$scope', 'Decisions', function ($scope, Decisions){

                //this prints undefined
                console.log($scope.decisionType);

                //this prints the proper value when called a couple seconds after page load
                $scope.getDecisionType = function(){
                    console.log($scope.decisionType);
                };

                //this is my motivation for wanting $scope.decisionType to be bound immediately
                if($scope.decisionType==='hire'){
                    //should do some stuff here
                }
            }]
        };
    }]);

我这样称呼我的指令:

<decision-maker decision-type="investment"></decision-maker>
<decision-maker decision-type="hire"></decision-maker>
4

2 回答 2

4

您将要使用该$observe功能。请参阅指令文档的属性部分。

所以,像这样:

        controller: ['$scope', '$attrs', 'Decisions', function ($scope, $attrs, Decisions){

            //this prints undefined
            console.log($scope.decisionType);

            //this prints the proper value when called a couple seconds after page load
            $scope.getDecisionType = function(){
                console.log($scope.decisionType);
            };

            $attrs.$observe('decisionType', function(value) {
                //this is my motivation for wanting $scope.decisionType to be bound immediately
                if($scope.decisionType==='hire'){
                    //should do some stuff here
                }

            });
        }]
于 2013-09-17T20:48:25.610 回答
0

我可以通过 $attrs 对象更直接地访问它们,而不是尝试通过将它们与范围绑定来访问我的属性!

angular.module('startup.directives.decision', [])

    .directive('decisionMaker', [function () {
        return{
            restrict: 'E',
            templateUrl: 'views/directives/decision.html',
            scope: {}, 
            controller: ['$scope', '$attrs', 'Decisions', function ($scope, $attrs, Decisions){

                //this prints the correct value
                console.log($attrs.decisionType);

                if($attrs.decisionType==='hire'){
                    //should do some stuff here
                }
            }]
        };
    }]);
于 2013-09-18T15:20:09.017 回答