是否可以从一个指令模板向另一个指令模板发送值/ ng模型? (AngularJS)

时间:2014-10-01 05:45:11

标签: javascript html angularjs templates directive

让我们想一想这里最简单的例子。

如何从指令A的模板中发送文本输入的值作为指令B模板中以ng-repeat形式存在的列表的过滤器?

1 个答案:

答案 0 :(得分:0)

第一种方法 - 依赖主机控制器的范围http://plnkr.co/edit/WuEN9hgfSoiIpR8ufocW?p=preview

<强> HTML

<first-directive></first-directive>
<second-directive></second-directive>

<强> JS

app.controller('myCtrl',function($scope, $location, $timeout) {

    $scope.items=['a ab', 'asd', 'www', '123'];
  }
);

app.directive('firstDirective', function() {
   return {
      restrict: 'EA',
      scope: false,
      template: '<div><input ng-model="input"></div>'
    };
});


app.directive('secondDirective', function() {
   return {
      restrict: 'EA',
      scope: false,
      template: '<div ng-repeat="item in items | filter:input">{{ item }}</div>'
    };
});

第二种方法 - 指令参数http://plnkr.co/edit/zEJWgQfLgVzl2RpO3qhp?p=preview

<强> HTML

<first-directive filter-string="filterString"></first-directive>
<second-directive filter-string="filterString" items="items"></second-directive>

<强> JS

app.controller('myCtrl',function($scope, $location, $timeout) {
    $scope.items=['a ab', 'asd', 'www', '123'];
    $scope.filterString = '';
  }
);

app.directive('firstDirective', function() {
   return {
      restrict: 'EA',
      scope: { filterString:"=" },
      template: '<div><input ng-model="filterString"></div>'
    };
});


app.directive('secondDirective', function() {
   return {
      restrict: 'EA',
      scope: { filterString:"=",
      items:"="},
      template: '<div ng-repeat="item in items | filter:filterString">{{ item }}</div>'
    };
});