如何在 AngularJS 中的另一个控制器中使用来自控制器的变量 [英] How to use variables from a controller in another controller in AngularJS
问题描述
我是 AngularJS 的新手,我想使用我在这个控制器中获得的 username
和 password
变量:
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state, Api) {$scope.data = {};$scope.login = function() {LoginService.loginUser($scope.data.username, $scope.data.password).成功(功能(数据){$scope.data = {}$state.go('tabs.extranet');}).错误(功能(数据){var alertPopup = $ionicPopup.alert({title: 'Acceso denegado',模板:'Por 青睐,compruebe su usuario y/o contraseña'});$state.go('tabs.extranet');});};})
在这个控制器内部
.controller('SaesoTabCtrl', function($scope, $sce, Saeso, Api){//一些代码....}
谢谢
您可以将变量添加到 $rootScope
并使用 $rootScope.varname
在任何控制器中访问它们.
这不是一个好的做法,因为它本质上类似于引入全局 Angular 变量.
一种更好的方法(在您的情况下可能有效也可能无效)是定义两个控制器,如下所示:
<!-- 此处仅可访问 MainController --><div ng-controller="InnerController"><!-- MainController 和 InnerController 都可以在这里访问--><!-- 主控制器 $scope 变量也应该可以在 InnerController 中访问 -->
如果您尝试后一种方法以了解它是否有效,我会很感兴趣.这展示了视觉继承.也许你可以为此做一个plunker?
I'm new in AngularJS and I want to use the username
and password
variables that I get in this controller:
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state, Api) {
$scope.data = {};
$scope.login = function() {
LoginService.loginUser($scope.data.username, $scope.data.password)
.success(function(data) {
$scope.data = {}
$state.go('tabs.extranet');
})
.error(function(data) {
var alertPopup = $ionicPopup.alert({
title: 'Acceso denegado',
template: 'Por favor, compruebe su usuario y/o contraseña'
});
$state.go('tabs.extranet');
});
};
})
Inside this controller
.controller('SaesoTabCtrl', function($scope, $sce, Saeso, Api){
//some code....
}
Thanks
You can add vars to $rootScope
and access them in any controller using $rootScope.varname
.
This is not good practice because its essentially similar to introducing global Angular variables.
A better approach, which may or may not work in your situation, is to define two controllers as follows:
<body ng-controller="MainController">
<!-- only MainController is accessible here -->
<div ng-controller="InnerController">
<!-- both MainController and InnerController are accessible here -->
<!-- main controllers $scope variables should also be accessible in InnerController -->
</div>
</body>
I would be interested if you try the latter approach to know if you got it working. This demonstrates scopical inheritance. Maybe you can make a plunker for this?
这篇关于如何在 AngularJS 中的另一个控制器中使用来自控制器的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!