【发布时间】:2017-04-08 12:30:22
【问题描述】:
Ng-table(ng-table site) 可以将$data 变量从他们的指令放到“用户”域之外。只要我知道,我可以随意使用和滥用这个$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 索引.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 变量暴露在外部,这样我就可以在index.html 中使用它,就像上面的ng-table 示例一样。如何做到这一点?
【问题讨论】:
-
你试过
{{ variable }}<div>吗? -
你可以在 plnkr.co/edit/UmDWM2rBnYVuMxXcEACM?p=preview 中测试它,是的,我试过了,正如我所料,它没有显示任何内容,因为
variable在指令之外 -
我不确定我是否得到你的问题。这能解决你的问题吗? plnkr.co/edit/RTa2dObiF1hLyIdae6Ba?p=preview
-
不,我只是对问题的结尾做了一些小修改。我希望
foo暴露在指令之外,而不是variable。查看plnkr.co/edit/0ShOpcRz1aVTFEKeQe35?p=preview,它显示hello world,它来自指令本身内部 -
@RogerNg 是的,它解决了我的问题,但我还有另一个问题:这个解决方案不适用于较新的 Angular 版本,或者我做错了。请在此处查看,这是您参考中的一个更简单的版本:plnkr.co/edit/UmDWM2rBnYVuMxXcEACM?p=preview,请注意它适用于 1.0.1,不适用于 1.3x 或 1.5x(“你好”不显示)
标签: angularjs