我是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,應關閉對話框,但現在測試的原因,如果是調用事件
Toptal對'$ emit' vs'$ broadcast'的解釋有助於:http://www.toptal.com/angular-js/videos/javascript-video-tutorial-understanding-broadcast-and-emit-in- angularjs –