我的指令有一个控制器,我试图弄清楚如何从传入的指令中传递一个值。在下面的例子中,' 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;
答案 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);
}
};
});