[英]Angular call controller function from nested custom directive
我可以幫忙。 我有一個包含名為“ loadInformation()”的函數的控制器。 在此控制器內部,我使用的服務正在使用自定義指令進行一些DOM操縱。 這些是指令:
第一個自定義指令:
angular.module('...').directive('ngInputString', function () {
return {
restrict: 'AE',
replace: 'true',
scope: {
savedInformation: '=',
type: '@',
values: '='
},
templateUrl: 'directives/templates/inputString.html',
link: function (scope, element, attrs) {
scope.filterOb = {ttype: scope.type};
}
}
});
HTML檔案:
<div>
<input ttype="{{type}}" type="text" placeholder="{{param.name}}" value='{{param.value}}'
class='clean-input form-control'/>
<ng-saved-information type="STRING" saved-information="savedInformation"></ng-saved-information>
</div>
嵌套的自定義指令:
angular.module('semtrosApp').directive('ngSavedInformation', function () {
return {
restrict: 'AE',
replace: 'true',
scope: {
savedInformation: '=',
type: '@'
},
template: '<ul><li ng-repeat="information in savedInformation | filter:filterOb">{{information.value}}<button type="button" ng-click="..?..">Use Information</button></li></ul>',
link: function (scope, elem, attrs) {
scope.filterOb = {ttype: scope.type};
}
}
});
當我不使用嵌套指令時,它與那段代碼配合就可以了:
elem.bind('click', function() {
scope.$apply(function() {
scope.loadInformation();
});
});
但是,當它們嵌套時,第二個自定義指令只是在父指令的范圍內查找。 知道如何通過函數調用嗎?
看起來ngInputString
指令已經接收了一些數據,並將其傳遞給ngSavedInformation
。 為什么還不接受loadInformation
回調並將其傳遞下去呢?
angular.module('...').directive('ngInputString', function () {
return {
scope: {
savedInformation: '=',
type: '@',
values: '=',
loadInformation: '&'
},
// etc
}
});
<ng-saved-information type="STRING" saved-information="savedInformation" load-information="loadInformation()"></ng-saved-information>
angular.module('semtrosApp').directive('ngSavedInformation', function () {
return {
scope: {
savedInformation: '=',
type: '@',
loadInformation: '&'
},
// etc
}
});
另外,您可以在模板中執行以下操作,而不是手動創建點擊處理程序:
ng-click="loadInformation()"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.