Ng-table(ng-table site)可以将$data
变量放在其指令之外的“用户”#39;域。只要我知道,我可以使用和滥用此$data
变量,只要它在<table ng-table></table>
内发生,就像这样:
<table ng-table="vm.tableParams" class="table" show-filter="true">
<tr ng-repeat="user in $data"> <---- where is this $data comes from ?
</tr>
</table>
我想对我的指令做同样的事情,所以我做了这个:
[JS]
angular.module('app', [])
.controller('Controller', ['$scope', function($scope) {
$scope.variable = "some random variable";
}])
.directive('myTable', function() {
return {
restrict : 'E',
transclude : true,
templateUrl : 'my-table.html',
controller: function($scope){
$scope.foo = "hello world";
}
};
});
[HTML my-table.html]
<div ng-transclude></div>
[HTML index.html]
<my-table ng-model="variable">
<div>{{ foo }}</div> <!-- foo comes from directive, not controller -->
</my-table>
它有效! working sample,
但是当我向指令添加scope
时:
return {
restrict: 'E',
transclude: true,
scope:{
ngModel : "="
},
templateUrl: 'my-table.html',
controller: function($scope){
$scope.foo = "hello world";
}
}
它会销毁foo
变量,因此它不再起作用not working sample。
我只想让foo
变量INSIDE指令暴露在外面,所以我可以在index.html
中使用它,就像上面的ng-table
示例一样。如何实现这一目标?
答案 0 :(得分:1)
如果您希望将foo
暴露在外面,请将foo
添加到指令的范围属性
return {
restrict: 'E',
transclude: true,
scope:{
ngModel : "=",
foo : "=" //here we state that foo INSIDE will be the same as passed from higher level
},
templateUrl: 'my-table.html',
controller: function($scope){
}
}
,模板看起来像这样
{{bar}}
<my-table ng-model="variable" foo="bar">
<div>{{ foo }}</div> <!-- this is internal 'foo' now which is equal to upper 'bar' value-->
</my-table>
以下是您的插件演示:https://plnkr.co/edit/VqmaxG2fIFO4k9JrQYRs?p=preview