我有一个指令供用户喜欢(或“收藏”)我的应用程序中的帖子。在我的整个控制器中,我使用$ rootScope。$ emit('功能名称',some-id)在用户喜欢新帖子时更新用户数据,因为这反映在我的应用程序中。但我似乎无法在指令中使用$ rootScope。$ emit。我收到一个错误
$ rootScope。$ emit不是函数
可能尚未调用与此命令相对应的$ rootScope。$ on事件,因此该函数尚不存在?关于这个还能做什么?有更好的方法来安排这个吗?
var module = angular.module('directives.module');
module.directive('postFave', function (contentService, $rootScope) {
return {
restrict: 'E',
templateUrl: 'directives/post-fave.html',
scope: {
contentId: '@',
slug: '@'
},
link: function ($scope, $rootScope, element) {
$scope.contentFavToggle = function (ev) {
contentId = $scope.contentId;
contentService.contentFavToggle(contentId, ev).then(function (response) {
$rootScope.$emit('dataUpdated', $scope.slug);
if (response) {
$scope.favourite[contentId] = response;
} else {
$scope.favourite[contentId] = null;
}
});
};
console.log("track fave directive called");
}
};
});
来自控制器:
var dataUpdatedListener = $rootScope.$on('dataUpdated', function (event, slug) {
dataService.clearData(slug);
dataControllerInit();
});
如何从指令中访问此rootscope函数?谢谢。
仅供参考-指令中使用了“链接”,因为它与HTML元素实例相关,该实例将在页面上多次使用
最佳答案
link
具有以下签名,无需在$rootScope
函数中添加link
注入:
function link(scope, element, attrs, controller, transcludeFn) { ... }
从
link
删除它,它将起作用。