[英]calling controller function from link function
我正在嘗試從鏈接函數調用控制器中的函數。 從控制器功能,我必須打個休息服務電話。 (我嘗試從link函數調用rest服務,但沒有成功。因此,我嘗試從link調用控制器函數,然后從那里調用rest服務)。
我的代碼如下。
app.directive('collection', function() {
return {
restrict: "E",
replace: true,
scope: {
collection: '=',
articleData: '=',
articleContent: '='
},
template: "<ul><member ng-repeat='member in collection' member='member' article-data='articleData' article-content='articleContent'></member></ul>"
}
});
app.directive('member', function($compile,$http) {
return {
restrict: "A",
replace: true,
scope: {
member: '=',
articleData: '=',
articleContent: '='
},
template: "<div><li><a href='#' ng-click='getContent(member.itemId)'>{{member.title}}</a></li></div>",
link: function(scope, element, attrs) {
scope.getContent = function(itemId) {
scope.testFunction(itemId);
}
if (angular.isArray(scope.member.tocItem)) {
if (scope.member.hasChildren == "true") {
for (var i = 0; i < scope.member.tocItem.length; i++) {
if (scope.member.tocItem.title) {
scope.member.tocItem.title.hide = true;
}
}
}
element.append("<collection collection='member.tocItem'></collection>");
$compile(element.contents())(scope)
}
}
}
});
app.controller('apdController', function($scope, getTocService,$location) {
var bookId = $location.search().id;
var sampdata = getTocService.getToc(bookId);
$scope.tasks =sampdata;
//$scope.tasks = data;
var artData = getTocService.getArtData('PH1234');
$scope.articleContent = artData;
$scope.testFunction = function(itemId){
alert("called.....");
}
});
在這里,我試圖從鏈接調用testFunction。我計划從testFunction調用rest服務。 但是獲取未定義不是函數錯誤。 有人可以幫忙嗎? 另外,請告訴我這是一種正確的方法(從鏈接函數到控制器,從控制器到rest調用。由於我的時間線較少,因此我無法想到其他方法)
testFunction
什么作用? 您有不同的選擇。 如果testFunction
調用rest服務,那么您絕對應該將其移至服務。
app.factory('restService', function($http) {
function testFunction(itemId){
// Whatever you need
return $http.get('myUrl');
}
return {
testFunction: testFunction
}
});
然后將其注入您的指令中
app.directive('member', function($compile, $http, restService) {
...
link: function(scope, element, attrs) {
scope.getContent = function(itemId) {
restService.testFunction(itemId);
}
....
}
});
這樣,如果需要,您也可以在控制器中調用它。 相反,如果您必須與控制器進行通訊,則可以使用信號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.