如何将变量置于角度指令之外?

时间:2016-11-24 09:25:56

标签: angularjs

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示例一样。如何实现这一目标?

1 个答案:

答案 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