我有一个结构非常简单的示例应用程序(您可以在这里看到它:http: //plnkr.co/edit/5VAqUQsqKFGoteahacR2 ?p=preview ):文件 index.html 包括模板(app/templates/home.html),反过来,它包括指令的模板:
<div class="included" ng-include="'app/templates/outer-directive-2.html'"></div>
它包括下一个指令:
<p>This is the included file <b>app/templates/outer-directive-2.html</b></p>
<div inner2="context"></div>
参数 inner2 的值是在 contentsCtrl 控制器中定义的 $scope.contents 对象的键:
app.controller('contentsCtrl', function($scope,$rootScope){
$scope.contents = {
context: "Context for investigations here."
}
});
需要这个键来提取指令脚本(app/scripts/directives/defaultDirective.js)中的对象字段:
app.directive('inner2', function(){
return{
restrict: 'A',
replace: true,
scope: {
inner2: '@',
contents: '&'
},
templateUrl: 'app/templates/inner-directive-2.html',
controller: function($scope){
$scope.getStuff = function(){
console.log('$scope.inner2, $scope.contents', {
// returns the key "context"
'$scope.inner2':$scope.inner2,
// returns function (???)
'$scope.contents':$scope.contents,
// returns "undefined"
'$scope.context':$scope.contents[$scope.inner2]
});
}
}
};
});
最后一个折叠指令(app/templates/inner-directive-2.html)的内容非常简单:
<div class="included" title="{{inner2}}">
<p>Hello, I am the inner directive 2</p>
<span class="pseudolink" ng-click="getStuff()">Click me</span> and check console message!
</div>
所以想法是通过调用 getStuff() 来获取 $scope.contents[object_key]。但它看不到$scope.contents。我认为可以通过将隔离范围参数(见上文)内容绑定到外部范围来完成:
scope: {
....
contents: '&'
},
...但它不返回范围对象,而是返回函数。可能这里出了点问题。问题是: 1. 为什么起作用,它从何而来?2. 我可以通过某种方式获得 $scope.contents 吗?如何获得?