我有一个嵌套在父div中的自定义指令,该控制器的控制器将变量 value 设置为其范围,例如:
HTML
<div ng-controller="mainCtrl">
<p>{{data}}</p>
<myDirective oncolour="green" offcolour="red" data="data"></myDirective>
</div>
的javascript
app.controller("mainCtrl", function($scope){
$scope.data= 1;
});
app.directive("myDirective", function() {
return {
restrict: 'E',
scope: {
oncolour: '@',
offcolour: '@',
data: '='
},
template: '<p>{{data}} is {{state}}</p>',
controller: function($scope){
console.log($scope.data); //undefined!
/* logic to set $scope.state depending on $scope.data */
};
};
});
我可以将数据的值传递给指令,因为我可以看到正确解析的模板中的 {{data}} 。
但是,指令的控制器中未定义 $ scope.data 。我需要根据这个变量应用一些逻辑,如如果data == 1,则state =“on”,else state =“off”,那么我可以应用 oncolour < / em>和 offcolour 。
知道如何实现这一目标吗?
答案 0 :(得分:2)
&#34; transclude&#34;选项是必要的:
transclude: true,
controller: ['$scope', function($scope) {
console.log($scope.data);
}],
答案 1 :(得分:0)
您错过了指令范围之前的$
。您将未定义的原因是因为指令$scope
与返回scope
不同。你必须匹配它们。
app.directive("myDirective", function() {
return {
restrict: 'E',
$scope: {
oncolour: '@',
offcolour: '@',
data: '='
},
template: '<p>{{data}} is {{state}}</p>',
controller: function($scope){
console.log($scope.data); //undefined!
/* logic to set $scope.state depending on $scope.data */
};
};
});
答案 2 :(得分:0)
将$scope
更改为scope
,查看angular directive documentation,转到页面末尾并查看示例代码
app.directive("myDirective", function() {
return {
restrict: 'E',
scope: {
oncolour: '@',
offcolour: '@',
data: '='
},
template: '<p>{{data}} is {{state}}</p>',
controller: function(scope){
console.log(scope.data); //undefined!
/* logic to set $scope.state depending on $scope.data */
};
};
});
答案 3 :(得分:0)
我敢打赌,由于数据是原语,绑定失败,请参阅https://github.com/angular/angular.js/wiki/Understanding-Scopes
尝试并更改:
Google={}
Google["Price"]=[317.68,396.05,451.48,428.03,516.26,604.83,520.63,573.48,536.51,542.84,533.85,660.87,728.9]
和
app.controller("mainCtrl", function($scope){
$scope.data= 1;
});
进入:
<div ng-controller="mainCtrl">
<p>{{data}}</p>
<myDirective oncolour="green" offcolour="red" data="data"></myDirective>
</div>
和
app.controller("mainCtrl", function($scope){
$scope.data= {
value: 1
};
});
答案 4 :(得分:0)