第一个View中点击按钮,通过ui-router跳转按钮到第二个View,在第二个controller中能接收到数据,赋值给$scope,但是页面上没显示。
第一个View:
查看
第一个controller中的方法:
$scope.checkUserInfo = function(userId) {
$rootScope.$broadcast('toUserInfo', userId);
}
第二个View:
- UserId:{{data.user.userId}}
- Name:{{data.user.name}}
- Sex:{{data.user.sex}}
- Birthday:{{data.user.birthday | date:'yyyy-MM-dd'}}
- Mobile:{{data.user.mobile}}
第二个controller:
userApp.controller('userInfoCtrl', ['$scope', '$http', '$rootScope', 'serverUrl', function($scope, $http, $rootScope, serverUrl) {
$rootScope.$on('toUserInfo', function(event, userId) {
console.log(userId); //能获取到ID
$scope.userId = userId;
$http.get(serverUrl + "/user/info?userId=" + userId).success(function(data) {
console.log(data); //有data
$scope.data = data.data; //赋值后页面不显示
})
})
}])
ui-router:
.state('index.usermng.userInfo',{
url: '/userInfo',
templateUrl: 'tpls/userInfo.html',
controller: 'userInfoCtrl'
})
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我勒个去,瞅了半天才明白你用
$rootScope的目的,就为了传个 ID 啊~也蛮拼的……你也别纠结为什么视图不显示了,还是跟你讲一下正确的做法吧。
首先是 ui-router 的写法:
然后,有了这个 state 之后,第一个视图就可以写成:
第一个控制器里就不需要
checkUserInfo方法了;第二个视图没什么问题,不用改了;第二个控制器如下:就这样。我在
resolve那里返回的是 promise,所以 controller 里接收的时候要用then方法。这样做的好处是可以在 http 请求完成之前有多一次机会让你干别的(比如弄个 loading 状态之类的事情);如果你不需要,也可以在resolve那里返回return $http.get(...).then(function(response) { return response.data }),这样在 controller 里就直接拿到数据本身了。