从链接函数调用控制器函数
calling controller function from link function
我正试图从链接函数调用控制器中的一个函数。从控制器功能,我必须调用一个休息服务调用。(我试着从链接函数调用rest服务,但没有成功。所以我试着通过链接调用控制器函数,然后我将调用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,我计划调用一个休息服务。但未定义并不是函数错误。有人能帮忙吗?此外,请让我知道这是一种正确的方法(从链接函数到控制器,从控制器到休息调用。由于我的时间线较少,我想不出其他方法)
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);
}
....
}
});
这样,如果你需要的话,你也可以在控制器中调用它。如果你必须与控制器通信,那么你可以使用信号。
相关文章:
- AngularJS,angular.element($0).scope()揭示了每个控制器的函数
- 为什么我的控制器没有启动函数.js脚本
- 从全局函数调用Ember控制器上的方法
- AngularJS:控制器中的函数被模板多次调用
- 在Angular中呈现DOM对象时,如何调用控制器中指定的函数
- Angular,从指令控制器中的控制器触发函数
- 如何在指令链接函数中使用从控制器传递的筛选器
- 从控制器Angularjs调用链接函数
- 角度指令控制器:参数不是函数,未定义
- 如何从页面中的jquery调用angular js函数控制器
- angularjs调用事件中控制器的一个函数
- 通过指令在控制器中执行javascript函数
- AngularJS执行指令模板中的控制器函数
- 从指令链接函数监视控制器作用域
- AngularJS:如何与其他控制器共享作用域函数和变量
- 如何在angular ui模态控制器中定义函数
- 当指令中已经给定作用域时,如何访问控制器中声明的函数
- AngularJS:如何调用指令中定义的函数'控制器的作用域
- 我是否需要将工厂调用放在控制器的函数中
- 如何在角函数控制器中传递绑定值