[英]AngularJS : sharing controller between states in angular-ui router
I have these router.js inside my ionic app , 我在离子应用程序中有这些router.js,
myapp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.myprofile', {
url: "/myprofile",
abstract: true,
views: {
'menuContent': {
controller : "myprofileCtrl",
templateUrl: "templates/myprofile.html"
}
}
})
.state('app.myprofile.info', {
url: "/info",
controller: "profileinfoCtrl",
templateUrl: "templates/profile/info.html"
})
.state('app.myprofile.location', {
url: "/location",
controller: "profilelocationCtrl",
templateUrl: "templates/profile/location.html"
})
$urlRouterProvider.otherwise('/');
});
I need a way to share controller scopes between myprofile state and myprofile.location state and myprofile.info state too . 我需要一种方法来在myprofile状态和myprofile.location状态以及myprofile.info状态之间共享控制器范围。
I am using ionic framework 我正在使用离子框架
in myprofileCtrl 在myprofileCtrl中
myapp.controller("myprofileCtrl",function($scope,Authy ,Auth,$http ,$rootScope){
$scope.view_loading = true;
Authy.can_go().then(function(data){
$scope.profile =data.profile;
});
});
in profilelocationCtrl 在profilelocationCtrl中
myapp.controller("profilelocationCtrl",function($scope,Authy ,Auth,$http ,$rootScope){
console.log($scope.profile);
});
I got undefined in the console 我在控制台中未定义
I think the problem is that since $scope.profile
is set after an ajax call, when the myprofile.location
state is reached initially, then profile variable is still undefined on the parent $scope
, what you could do is $watch
the profile variable, or better just broadcast an event downwards when you receive it fro the server call using $broadcast
. 我认为问题是因为$scope.profile
是在ajax调用之后设置的,当最初达到myprofile.location
状态时,在父$scope
上仍未定义profile变量,你可以做的是$watch
profile变量或者更好的是,当您使用$broadcast
从服务器调用收到它时,向下广播一个事件。
$broadcast
dispatches the event downwards to all child scopes, so you could do: $broadcast
将事件向下调度到所有子范围,因此您可以执行以下操作:
myapp.controller("myprofileCtrl",function($scope,Authy ,Auth,$http ,$rootScope){
$scope.view_loading = true;
Authy.can_go().then(function(data){
$scope.profile =data.profile;
$scope.$broadcast('profileSet', data.profile);
});
});
and in the myprofile.location` state: 并在myprofile.location`状态:
myapp.controller("profilelocationCtrl",function($scope,Authy,Auth,$http,$rootScope){
$scope.$on('profileSet', function(event, data) {
console.log(data);
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.