第一个View中点击按钮,通过ui-router跳转按钮到第二个View,在第二个controller中能接收到数据,赋值给$scope,但是页面上没显示。
第一个View:
<a type="button" ui-sref="index.usermng.userInfo" ng-click="checkUserInfo(item.id)" class="btn btn-primary">查看</a>
第一个controller中的方法:
$scope.checkUserInfo = function(userId) {
$rootScope.$broadcast('toUserInfo', userId);
}
第二个View:
<p class="tab-pane active tab-chrome" id="tab-chrome">
<p class="row feature">
<p class="col-md-12">
<ul class="list-group">
<li class="list-group-item">UserId:{{data.user.userId}}</li>
<li class="list-group-item">Name:{{data.user.name}}</li>
<li class="list-group-item">Sex:{{data.user.sex}}</li>
<li class="list-group-item">Birthday:{{data.user.birthday | date:'yyyy-MM-dd'}}</li>
<li class="list-group-item">Mobile:{{data.user.mobile}}</li>
</ul>
</p>
</p>
</p>
第二个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'
})
Here I go, it took me a long time to figure out the purpose of using
$rootScope
, just to transfer an ID~ It’s quite a struggle...Don’t worry about why the view is not displayed. Let me tell you the correct way.
The first is how to write ui-router:
Then, with this state, the first view can be written as:
There is no need for the
checkUserInfo
method in the first controller; there is nothing wrong with the second view and no need to change it; the second controller is as follows:That’s it. I'm in
resolve
那里返回的是 promise,所以 controller 里接收的时候要用then
方法。这样做的好处是可以在 http 请求完成之前有多一次机会让你干别的(比如弄个 loading 状态之类的事情);如果你不需要,也可以在resolve
那里返回return $http.get(...).then(function(response) { return response.data })
, so I can get the data itself directly in the controller.