我有一个指令,让用户喜欢(或“喜欢”)我的应用程序中的帖子。在我的 Controller 中,当用户喜欢新帖子时,我使用 $rootScope.$emit('name-of-function', some-id) 来更新用户数据,因为这在我的应用程序中得到了反射(reflect)。但我似乎无法在指令中使用 $rootScope.$emit 。我收到错误
$rootScope.$emit is not a function
想必这个命令对应的$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");
}
};
});
来自 Controller :
var dataUpdatedListener = $rootScope.$on('dataUpdated', function (event, slug) {
dataService.clearData(slug);
dataControllerInit();
});
如何从指令内访问此 rootscope 函数?谢谢。
仅供引用 - 指令中使用了“link”,因为这与将在页面上多次使用的 HTML 元素的实例相关
最佳答案
link
具有以下签名,无需在 link
函数中添加 $rootScope
注入(inject):
function link(scope, element, attrs, controller, transcludeFn) { ... }
从链接
中删除它,它就会起作用。
关于javascript - AngularJS rootScope.$从指令内发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137150/