編輯:修改了代碼,每stevuu的建議,以及增加了一個plunkr到here通過指令傳遞方法父指令
我目前正在試圖有一個孩子指令調用一個方法(解析)通過另一個指令一直到父指令,但我很難用我的方法識別問題。
現在的問題似乎是,儘管resolve()在按鈕上按預期方式被調用,但選定仍然未定義。
的HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Angular: directive using & - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<style type='text/css'>
</style>
</head>
<body ng-app="myApp">
<div grand-parent>
<span>selected: {{text}}</span>
<div parent resolve="resolve"></div>
</div>
</body>
</html>
而且JS:
var myApp = angular.module('myApp',[]);
myApp.directive('grandParent', function() {
return {
scope:{
resolve: "&"
},
link: function($scope, $element) {
$scope.resolve = function(selected){
$scope.text = selected
}
}
};
});
myApp.directive('parent', function(){
return{
scope: {
resolve: "&"
},
template: "<div child resolve='resolve'></div>"
};
});
myApp.directive('child', function() {
return {
scope: {
resolve: "&"
},
template: "<div>Click me!</div>",
link: function($scope, $element) {
$element.on("click", function(){
$scope.$apply(function(){
$scope.resolve({selected: "Yahoo!!"});
});
});
}
};
});
首先,你不''決定''範圍''''在'grandParent'!應該讀一些像'$ scope.resolve = ...'的東西。 –
你的指令是否需要使用隔離範圍?如果不是,則在所有其他指令中都可以使用在grandParent範圍上定義的任何方法。 –