2016-11-24 14 views
1

我想将父指令的值传递给子指令。在这种情况下,父指令有一个函数,需要在点击子指令的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

回答

0

我已经更新您的JSFiddle恰当的解决方案。

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

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

并传递一个对象作为你的子指令中的键。

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

Awsome !! 我的坏我没有指定父指令:( 参数可是为什么我必须通过参数作为?? 键{值:data.name}为什么只有data.name没有工作? –

+0

不用担心,这是一个非常常见的错误,这就是AngularJS的工作原理 – Puigcerber

+0

可能[this](http://www.codelord.net/2016/05/13/understanding-angulars-and-binding/)是一种很好的文章解释了为什么。 – Puigcerber

相关问题