我正在遷移到基於Angular的前端。我有一個功能JavaScript
將一些數據傳遞給指令,經過一些研究發現使用Service
和$broadcast
可能是一個很好的解決方案。但不爲我工作...
這裏是我的代碼:
function _ajaxCUSTOMER(e) {
angular
.injector(['ng' ,'app'])
.get("broadcastService")
.sendAjaxResut("b1", e);
}
<button onclick="_ajaxCUSTOMER('foo')" >Send</button>
問題1:
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')
});
}
}
}
將數據傳遞到服務代碼是什麼ng
在.injector(['ng' ,'app'])
問題2:此時控制檯只顯示-- $broadcast
。什麼是我的代碼無法在指令捕捉事件的問題
@SuperComputer你可以在控制檯上看到「' - directive」「嗎? – Mironline
我用[你的解決方案](https://jsfiddle.net/9u2gqzw5/4/)修改了我的代碼,起初,調用service方法有問題,請你重新檢查你的代碼並更新[jsfiddle](https: //jsfiddle.net/9u2gqzw5/4/),謝謝 – Mironline