如何将值传递给有角度的指令控制器?

时间:2016-05-01 04:43:07

标签: javascript angularjs scope controller directive

我的指令有一个控制器,我试图弄清楚如何从传入的指令中传递一个值。在下面的例子中,' name'是无效的发布到控制台,但它在渲染时显示在html中。显然,我的例子是过度简化,但你明白了。



angular.module('myApp')
    .directive('helpLabel', function() {
        return {
            restrict: 'E',
            scope: {
                name: '@',
            },
            template: '<span>{{name}}</span>',
            controller: function ($scope) {                
                console.log(name);
            } 
        };
    });
&#13;
<helpLabel name="test"></helpLabel>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

我找到的答案是使用bindToController和controlsAs现在有效的角度1.4。

angular.module('myApp')
.directive('helpLabel', function() {
    return {
        restrict: 'E',
        scope:{},
        bindToConroller: {
            name: '@',
        },
        template: '<span>{{cntrl.name}}</span>',
        controller: function () {                
            console.log(cntrl.name);
        },
        controllerAs: "cntrl"
    };
});

http://blog.thoughtram.io/angularjs/2015/01/02/exploring-angular-1.3-bindToController.html

答案 1 :(得分:0)

这是因为在将其呈现给html时,您将名称封装在{{}}中。如果您不想访问指令中的name属性,则必须更改代码。

angular.module('myApp')
.directive('helpLabel', function() {
    return {
        restrict: 'E',
        scope: {
            name: '@',
        },
        template: '<span>{{name}}</span>',
        controller: function ($scope) {                
            console.log($scope.name);
        } 
    };
});

答案 2 :(得分:0)

在您的代码console.log(name);中,变量name不知道您的指令,因此无法访问它,但由于angular已绑定到'name'变量,因此它可以呈现{{name}}

您应该将变量name作为$scope.name访问,因为当前范围内存在变量name

修改您的代码如下:

angular.module('myApp')
    .directive('helpLabel', function() {
        return {
            restrict: 'E',
            scope: {
                name: '@',
            },
            template: '<span>{{name}}</span>',
            controller: function ($scope) {                
                console.log($scope.name);
            } 
        };
    });