如何在控制器中的隔离范围中使用绑定值

时间:2013-09-17 20:41:00

标签: angularjs angularjs-directive angularjs-scope

我有一个指令。我想在我的指令控制器中使用该指令的属性值。我尝试通过将属性值绑定到我的隔离范围来完成此操作。但是我遇到了一个问题,因为属性值似乎没有立即绑定到隔离范围。

请考虑以下代码:

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>

2 个答案:

答案 0 :(得分:4)

您将要使用$observe功能。请参阅Directives documentation

的“属性”部分

所以,像这样:

        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
                }

            });
        }]

答案 1 :(得分: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
                }
            }]
        };
    }]);