我有一条指令供用户喜欢(或“收藏”)我的应用程序中的帖子。在我的整个控制器中,我使用$ 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函数?谢谢。
FYI-指令中使用了“链接”,因为它与HTML元素的实例有关,该元素将在页面上使用多次