![](/img/trans.png)
[英]AngularJS calling Directive function with or without parameter from Controller
[英]calling function in a controller from a directive view, angularJS
我正在嘗試使用ng-click調用html指令中的兩個函數。 第一個功能“ checkUrl”位於指令控制器中,並且工作正常。
第二個功能“ findUrl”位於主應用程序控制器中,不會被觸發。
HTML:
<div class="status" ng-click="checkUrl()">
<b ng-click="checkUrl()">{{card.status}}</b>
</div>
<div ng-click="findUrl()" class="image">
<img ng-src={{card.image}} alt="">
</div>
我有一些問題:
1)這是因為兩個控制器具有不同的作用域,而一個控制器無法訪問另一個控制器嗎?
2)如何獲取指令view / html來調用主控制器功能?
指令的控制器:
$scope.checkUrl = function() {
console.log("invoking checkUrl from the directive's controller.")
asnService.showUrl();
};
應用控制器:
$scope.findUrl = function() {
console.log("invoking findUrl from the app controller");
asnService.showUrl();
};
要回答您的問題,可以使用$ scope。$ parent.findUrl()訪問指令父級作用域上的作用域變量。 不一定推薦,但可以。
這是3種方式:
第一
如果指令中沒有隔離范圍,則您的示例可以正常工作https://jsfiddle.net/vorant/waf8rta2/1/
第二
如果指令中的作用域被隔離,則將此代碼添加到指令的控制器中
$scope.findUrl = function() {
$scope.$parent.findUrl();
};
https://jsfiddle.net/vorant/waf8rta2/2/
最佳方式使用$emit
(指令必須具有隔離范圍)
指令的控制器:
$scope.findUrl = function() {
$scope.$emit('status:findUrl');
};
應用控制器:
$scope.$on('status:findUrl',function(){
$scope.findUrl();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.