JavaScript使用$ scope。$ emit和$ scope。$ on
首先,父子范圍關系確實很重要。你有兩種可能性發出某些事件:
$broadcast -將事件向下分發到所有子范圍,$emit-通過范圍層次結構向上調度事件。我對你的控制器(作用域)關系一無所知,但是有幾種選擇:
如果scope of firstCtrl是作用域的父級,則secondCtrl你的代碼應通過替換$emit為$broadcastin來工作firstCtrl:
function firstCtrl($scope){ $scope.$broadcast(’someEvent’, [1,2,3]);}function secondCtrl($scope){ $scope.$on(’someEvent’, function(event, mass) { console.log(mass); });}
如果你的范圍之間沒有父子關系,則可以注入$rootScope控制器并將事件廣播到所有子范圍(即secondCtrl)。
function firstCtrl($rootScope){ $rootScope.$broadcast(’someEvent’, [1,2,3]);}最后,當你需要將事件從子控制器分派到向上作用域時,可以使用$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方法將對象從一個控制器發送到另一個控制器?
function firstCtrl($scope) { $scope.$emit(’someEvent’,[1,2,3]);}function secondCtrl($scope) { $scope.$on(’someEvent’,function(mass) { console.log(mass); });}
它不按我認為的方式工作。如何做$emit和$on工作?
相關文章:
1. python - 如何判斷字符串為企業注冊名稱2. html - 移動端radio無法選中3. php - 微信開發驗證服務器有效性4. javascript - 我的站點貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?5. Python2中code.co_kwonlyargcount的等效寫法6. [python2]local variable referenced before assignment問題7. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?8. python中怎么對列表以區間進行統計?9. javascript - vue+iview upload傳參失敗 跨域問題后臺已經解決 仍然報403,這是怎么回事啊?10. mysql - 請問數據庫字段為年月日,傳進的參數為月,怎么查詢那個月所對應的數據
