【问题标题】:How to put variable outside angular directive? [duplicate]如何将变量放在角度指令之外? [复制]
【发布时间】: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 }}&lt;div&gt;吗?
  • 你可以在 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


【解决方案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>

这里是你的 plunk 的演示:https://plnkr.co/edit/VqmaxG2fIFO4k9JrQYRs?p=preview

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 2013-09-17
  • 2016-08-25
  • 2020-10-27
  • 2016-11-24
相关资源
最近更新 更多