我正在迁移到基于Angular的前端。我在JavaScript
中有一个函数将一些数据传递给指令,经过一些研究发现使用Service
和$broadcast
可能是一个很好的解决方案。但对我不起作用......
这是我的代码:
var app = angular.module('app', []);
app.factory('broadcastService', ['$rootScope',
function($rootScope) {
var factory = {};
factory.sendAjaxResut = function(name, obj) {
console.log(' -- $broadcast ');
$rootScope.$broadcast(name, obj);
}
return factory;
}
]);
app.directive("bill", [directive]);
function directive() {
return {
restrict: "E",
link: function($scope) {
$scope.$on("b1", function(e, a) {
console.log('-- directive')
});
}
}
}
将数据传递给服务的代码:
function _ajaxCUSTOMER(e) {
angular
.injector(['ng' ,'app'])
.get("broadcastService")
.sendAjaxResut("b1", e);
}
<button onclick="_ajaxCUSTOMER('foo')" >Send</button>
问题1:ng
.injector(['ng' ,'app'])
是什么
问题2:此时控制台仅显示-- $broadcast
。我的代码无法在指令
答案 0 :(得分:1)
您的指令未获得$ broadcast,因为您正在使用新的$ rootScope创建新的注入器。而是使用您的应用程序的注入器。
function _ajaxCUSTOMER1(e) {
var rawElem = document.getElementById("app");
var elem = angular.element(rawElem);
var _injector = elem.injector();
var _broadcastService = _injector.get("broadcastService");
_broadcastService.sendAjaxResut("b1",e);
}
此示例查找应用的元素,并使用angular.element
检索其注入器。
答案 1 :(得分:0)
你可以尝试这个解决方案:
<button onclick="_ajaxCUSTOMER('foo', 'e')" >Send</button>
function _ajaxCUSTOMER(name,obj) {
angular.element(document).find('body').injector().get('broadcastService').sendAjaxResut(name, obj);
console.log('ok');
}
myApp.factory('broadcastService', ['$rootScope',
function($rootScope) {
console.log('broadcastService');
var factory = {};
factory.sendAjaxResut = function(name, obj) {
console.log(' -- $broadcast ');
$rootScope.$broadcast('newEvent', name, obj);
}
return factory;
}
]);
myApp.directive('bill', function () {
return {
restrict: 'EAC',
controller: function($scope) {},
link: function(scope, element, attrs) {
scope.$on("newEvent", function(event, data, name, obj) {
console.log('-- directive')
});
}
};
});
答案 2 :(得分:0)
您需要在html
中定义控制器。
jsfiddle上的实例。
var app = angular.module('app', [])
.controller('ExampleController', function($scope, broadcastService) {
});
app.factory('broadcastService', ['$rootScope',
function($rootScope) {
var factory = {};
factory.sendAjaxResut = function(name, obj) {
console.log(' -- $broadcast ');
$rootScope.$broadcast(name, obj);
}
return factory;
}
]);
app.directive("bill", function($rootScope) {
return {
restrict: "E",
template:'<div>My bill</div>',
link: function($scope) {
$rootScope.$on("b1", function(e, a) {
console.log('-- directive',a)
});
}
}
});
function _ajaxCUSTOMER1(e) {
angular.element(document).find('body').injector().get('broadcastService').sendAjaxResut('b1', e);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body id="app" ng-app="app">
<div ng-controller="ExampleController">
<button onclick="_ajaxCUSTOMER1('5')">
Click Here to send 5
</button>
<bill>
</bill>
</div>
</body>