2015-06-15 77 views
5

我是angularjs的新手,我正在創建一個Web應用程序以賺取經驗和實踐。我遇到的問題是,$scope.$emit似乎沒有工作,我正在尋找方法來控制控制器之間的功能,到目前爲止,我在互聯網上發現,$scope.emit$scope.on似乎適合這種任務,如果有另一個這樣,我想知道,反正代碼都是這樣寫的:

loginController.js

(function(angular) 
{ 
    var app = angular.module('Organizer'); 

    // inject $scope to the controller in order to try $scope.$emit 
    app.controller('login', function($http, $scope) 
    { 
     // i define the scope like this so i can access inside other functions 
     var scope = this; 
     scope.processing = false; 
     scope.message = null; 

     scope.submit = function() 
     { 
      scope.processing = true; 

      // store data for post 
      var post = { 
       username: scope.username, 
       password: scope.password 
      }; 

      // send post data 
      $http.post('api/default/login', post). 
       success(function(data, status) 
       { 
        // hide processing feedback and show the result 
        scope.processing = false; 
        scope.message = data.message; 
       }). 
       error(function(data, status) 
       { 
        scope.processing = false; 
       }); 
     }; 

     // Function i use to emit 
     this.closeDialog = function() 
     { 
      $scope.$emit('closeDialog'); 
     }; 
    }); 
})(angular); 

siteController.js

(function(angular) 
{ 
    var app = angular.module('Organizer'); 

    app.controller('site', function($mdDialog, $scope) 
    { 
     this.menu = ['test1', 'test2']; 

     this.dialog = function() 
     { 
      $mdDialog.show({ 
       templateUrl: 'site/login', 
      }); 
     }; 

     // this does not seem to be working 
     $scope.$on('closeDialog', function(event) 
     { 
      console.log('close dialog'); 
     }); 
    }); 
})(angular); 

注:我正在使用角材料,你可以看到我顯示一個對話框,這是一個登錄,登錄有它的控制器(我想它使用相同的站點控制器,但我不知道如何),這個對話框有一個按鈕,調用函數closeDialog()在loginControler,應關閉對話框,但現在測試的原因,如果是調用事件

+0

Toptal對'$ emit' vs'$ broadcast'的解釋有助於:http://www.toptal.com/angular-js/videos/javascript-video-tutorial-understanding-broadcast-and-emit-in- angularjs –

回答

8

我只是記錄的$發出功能傳播的事件只對父母範圍。

$ broadcast函數將一個事件傳播給作用域的孩子。

所以你需要什麼取決於控制器是如何使用它...

如果你想要一個事件,達到你所使用$ rootScope應用:

$rootScope.$broadcast('myEvent'); 

Here you have the doc of the scope, include $emit and $broadcast

+0

謝謝你讓這個函數起作用,我也在想如果有另外一種方法來使用'$ controller'來實現這個方法,但是我還得學習如何恰當地使用角度,只是最後一個問題,有沒有在單個控制器中動態加載這些內容的方式?我不得不創建另一個控制器,它是'loginController'爲了使用它 – nosthertus

+0

對不起,我不明白你的問題,你是什麼意思? –

+0

正在使用LoginController的內容正在通過ajax加載,我想在siteController中的mdDialog上,我曾經嘗試在這個內容中使用相同的siteController範圍,但我不知道爲什麼它不起作用,所以我使用一個不同的控制器 – nosthertus

0

您無法在對話框控制器中發射或廣播,因爲角度材質中的對話框具有隔離範圍。因此,當你發射或廣播一個事件時,它不會去任何地方。 $ emit和$ broadcast只適用於你有範圍層次結構。 $向層次結構傳播事件,$廣播傳播事件層次結構。