我认为这很简单,但是如何通过将函数存储在'.run'阶段来获得我可以在控制器中访问的全局函数?
很简单,在DOM中单击一个按钮,触发在相应控制器中调用的全局函数。
我尝试了各种方法,并且想要一种非常简单的方法,这有助于最大限度地减少我目前获得的代码量。见下文:
**HTML**
<input data-ng-click="clearSignInError()" data-ng-model="email"
type="email"
id="inputEmail" class="form-control" placeholder="Email address"
required>
**JS**
app.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScopecope.clearSignInError = function () {
$rootScope.loginError = null;
$rootScope.loginSuccess = null;
};
}]);
app.controller('loginCtrl', ['$scope', 'Auth', '$state', '$rootScope'
function($scope, Auth, $state, $rootScope) {
$rootScope.clearSignInError()
}]);
答案 0 :(得分:1)
您最好的选择可能是使用服务或工厂,然后在整个应用程序中根据需要将这些作为依赖项注入。
编辑:在此plunkr中添加了一个示例服务
https://plnkr.co/edit/zqWS9gkTsm2OF1FTb24Z?p=preview
app.service('AuthService', function() {
this.loginSuccess = function() {
// do stuff when login is successful
}
this.loginError = function() {
// handle login errors here
}
this.clearLoginError = function() {
console.log("Clear Login Error");
alert("Clear Login Error");
}
});
// modified your controller
app.controller('loginCtrl', ['$scope', 'Auth', 'AuthService', '$state', '$rootScope', function($scope, Auth, AuthService, $state, $rootScope) {
$scope.clearSignInError = AuthService.clearLoginError;
}]);
**HTML**
<input data-ng-click="clearSignInError()" data-ng-model="email"
type="email" id="inputEmail" class="form-control" placeholder="Email address" required>
答案 1 :(得分:1)
您可以使用工厂而不是使用rootScope连接。通过这种方式,您可以将工厂作为依赖项包含在所需的任何控制器中。这是一个可以帮助您入门的视频演示: