JavaScript使用$ scope$ emit和$ scope$ on
首先,父子范圍關(guān)系確實很重要。你有兩種可能性發(fā)出某些事件:
$broadcast -將事件向下分發(fā)到所有子范圍,$emit-通過范圍層次結(jié)構(gòu)向上調(diào)度事件。我對你的控制器(作用域)關(guān)系一無所知,但是有幾種選擇:
如果scope of firstCtrl是作用域的父級,則secondCtrl你的代碼應(yīng)通過替換$emit為$broadcastin來工作firstCtrl:
function firstCtrl($scope){ $scope.$broadcast(’someEvent’, [1,2,3]);}function secondCtrl($scope){ $scope.$on(’someEvent’, function(event, mass) { console.log(mass); });}
如果你的范圍之間沒有父子關(guān)系,則可以注入$rootScope控制器并將事件廣播到所有子范圍(即secondCtrl)。
function firstCtrl($rootScope){ $rootScope.$broadcast(’someEvent’, [1,2,3]);}最后,當(dāng)你需要將事件從子控制器分派到向上作用域時,可以使用$scope.$emit。如果的范圍firstCtrl是范圍的父級secondCtrl:
function firstCtrl($scope){ $scope.$on(’someEvent’, function(event, data) { console.log(data); });}function secondCtrl($scope){ $scope.$emit(’someEvent’, [1,2,3]);}解決方法
如何$scope使用.$emit和.$on方法將對象從一個控制器發(fā)送到另一個控制器?
function firstCtrl($scope) { $scope.$emit(’someEvent’,[1,2,3]);}function secondCtrl($scope) { $scope.$on(’someEvent’,function(mass) { console.log(mass); });}
它不按我認為的方式工作。如何做$emit和$on工作?
相關(guān)文章:
1. mysql - 請問數(shù)據(jù)庫字段為年月日,傳進的參數(shù)為月,怎么查詢那個月所對應(yīng)的數(shù)據(jù)2. node.js - win 下 npm install 遇到了如下錯誤 會導(dǎo)致 無法 run dev么?3. javascript - js判斷一個數(shù)組是否重復(fù)4. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?5. [python2]local variable referenced before assignment問題6. Python2中code.co_kwonlyargcount的等效寫法7. html - 移動端radio無法選中8. php - 微信開發(fā)驗證服務(wù)器有效性9. javascript - vue+iview upload傳參失敗 跨域問題后臺已經(jīng)解決 仍然報403,這是怎么回事啊?10. mysql - 如何在有自增id的情況下,讓其他某些字段能不重復(fù)插入
