Angular1.3:递归指令模板中的访问控制器函数?
Angular1.3: Access controller function inside recursive directive template?
我可以使用 $parent 运算符在我的父指令中访问一次控制器函数,但这在递归子指令中不起作用。
下面是我的代码示例(为此我尝试将其缩短了一点):
//控制器示例(使用controllerAs定义):---
var View2Ctrl = function(){
//function i am trying to access:
this.getNumber = function(){
return 5;
}
.
.
.
angular.controller('View2Ctrl',............
//'comments' 指令模板:--
<li>
<!-- I'm trying to access the function in here: -->
<!-- below line works just once here, does not load in recursive child directives below: -->
<strong> Number: </strong> {{ $parent.View2Ctrl.getNumber() }}
<!-- below line gets replaced with a recursive child directive again -->
<span class="comments-placeholder" ></span>
</li>
//'comments' directive.js:---
var comments = function($compile){
return {
templateUrl : 'modules/comments/commentsDirective.html',
restrict:'E',
scope:{
collection: '='
},
link: function(scope, element, attrs){
if(scope.collection.data.replies){
var elementResult = angular.element(element[0].getElementsByClassName('comments-placeholder'));
elementResult.replaceWith($compile('<ul ng-repeat="comment in collection.data.replies.data.children><comments collection="comment"></comments></ul>')(scope));
}
}
};
};
您可以使用require
访问父控制器的this
。
var comments = function($compile){
return {
...
require: '^ngController',
link: function(scope, element, attrs, ctrl){
$scope.number = ctrl.getNumber();
}
};
};
但是拥有一个充当模型并为控制器和指令保存数据的服务总是更好。
我可以使用 $parent 运算符在我的父指令中访问一次控制器函数,但这在递归子指令中不起作用。 下面是我的代码示例(为此我尝试将其缩短了一点):
//控制器示例(使用controllerAs定义):---
var View2Ctrl = function(){
//function i am trying to access:
this.getNumber = function(){
return 5;
}
.
.
.
angular.controller('View2Ctrl',............
//'comments' 指令模板:--
<li>
<!-- I'm trying to access the function in here: -->
<!-- below line works just once here, does not load in recursive child directives below: -->
<strong> Number: </strong> {{ $parent.View2Ctrl.getNumber() }}
<!-- below line gets replaced with a recursive child directive again -->
<span class="comments-placeholder" ></span>
</li>
//'comments' directive.js:---
var comments = function($compile){
return {
templateUrl : 'modules/comments/commentsDirective.html',
restrict:'E',
scope:{
collection: '='
},
link: function(scope, element, attrs){
if(scope.collection.data.replies){
var elementResult = angular.element(element[0].getElementsByClassName('comments-placeholder'));
elementResult.replaceWith($compile('<ul ng-repeat="comment in collection.data.replies.data.children><comments collection="comment"></comments></ul>')(scope));
}
}
};
};
您可以使用require
访问父控制器的this
。
var comments = function($compile){
return {
...
require: '^ngController',
link: function(scope, element, attrs, ctrl){
$scope.number = ctrl.getNumber();
}
};
};
但是拥有一个充当模型并为控制器和指令保存数据的服务总是更好。