【问题标题】:Pass value from one directive to another using function binding '&'使用函数绑定“&”将值从一个指令传递到另一个指令
【发布时间】:2016-11-24 20:23:32
【问题描述】:

我想将一个值从父指令传递给子指令。在这种情况下,父指令有一个函数需要在单击子指令的 div 时执行,并将 ng-model 值从子指令传递给父指令的调用函数。

http://jsfiddle.net/Lvc0u55v/12543/

var myApp = angular.module('myApp', []);
myApp.directive('parentDirective', function() {
  return {
    restrict: 'EA',
    transclude: true,
    template: '<div>Parent directive</div>',
    link: function(scope) {
      scope.someFunc = function(value) {
        alert(value);
      }
    }
  }
});
myApp.directive('childDirective', function() {
  return {
    restrict: 'EA',
    template: '<input type="text" ng-model="data.name"><button ng-click="issue(data.name)">Child Directive</button>',
    scope: {
      issue: '&'
    }
  }
});
<div ng-app="myApp">
  <parent-directive ng-transclude>
    <child-directive issue="someFunc()"></child-directive>
  </parent-directive>
</div>

JSfiddle link

【问题讨论】:

    标签: javascript html angularjs angularjs-directive


    【解决方案1】:

    我已经用正确的解决方案更新了您的JSFiddle

    在父指令中绑定函数时需要指定参数。

    <child-directive issue="someFunc(value)"></child-directive>
    

    并将带有这些参数的对象作为子指令中的键传递。

    <button ng-click="issue({ value: data.name })">Child Directive</button>
    

    【讨论】:

    • 太棒了!我的错误是我没有在父指令中指定参数:(但是为什么我必须将参数作为键传递?? { value: data.name} 为什么只有 data.name 不起作用??
    • 不用担心。这是一个很常见的错误。这就是 AngularJS 的工作原理。
    • this 可能是一篇很好的文章来解释原因。
    • 感谢您的回答!但我仍然不明白为什么我需要传递一个对象? - 我很好奇 :D 如果你能回答我,那就太好了,或者请告诉我应该在哪里寻找答案。
    猜你喜欢
    • 2016-12-22
    • 2022-01-13
    • 1970-01-01
    • 2017-07-23
    • 2019-09-26
    • 2014-09-06
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多