我是angular的新手。所以我使用$ state来改变视图状态。我的状态代码是
angular.module('myApp.controller', []).controller('firstController', ['$scope', '$state', function($scope, $state) {
$scope.loadView2 = function() {
$state.go('secondView', {
firstname: $scope.firstname,
lastname: $scope.lastname
});
};
}]);
angular.module('myApp.controller').controller('secondController',
function($scope, $stateParams, $state) {
console.log($state.params); // empty object
$scope.firstname = $stateParams.firstname; // empty
$scope.lastname = $stateParams.lastname; //empty
});
我的路线正在跟随
angular.module('myApp', ['myApp.controller', 'ui.router']).config(['$stateProvider', function($stateProvider) {
$stateProvider.state('firstView', {
url: '/fisrt-view',
templateUrl: './partials/view1.html',
controller: 'firstController'
});
$stateProvider.state('secondView', {
url: '/second-view',
templateUrl: './partials/view2.html',
controller: 'secondController'
});
但我总是在view2中得到空白对象。
答案 0 :(得分:2)
在您必须在第二个视图中定义params的视图之间传递数据,如下所示:
$stateProvider.state('secondView', {
url: '/second-view',
templateUrl: './partials/view2.html',
controller: 'secondController',
params: {
mynewparam: null
}
});
然后切换视图时:
$state.go('secondView', {mynewparam: 'newParam'});
你可以像这样在视图控制器中检索数据:
$scope.mynewparam = $stateParams.mynewparam;
另请注意,您可以在不重复$ stateProvider的情况下链接状态,例如:
$stateProvider
.state('firstView', {
url: '/fisrt-view',
templateUrl: './partials/view1.html',
controller: 'firstController'
})
.state('secondView', {
url: '/second-view',
templateUrl: './partials/view2.html',
controller: 'secondController',
params: {
mynewparam: null
}
});
答案 1 :(得分:0)
您必须按如下方式定义参数:
$stateProvider.state('secondView', {
url: '/second-view?firstname&lastname',
templateUrl: './partials/view2.html',
controller: 'secondController'
});
或:
$stateProvider.state('secondView', {
url: '/:firstname/:lastname/second-view',
templateUrl: './partials/view2.html',
controller: 'secondController'
});
或:
$stateProvider.state('secondView', {
url: '/second-view',
templateUrl: './partials/view2.html',
controller: 'secondController',
params: {
firstname: null,
lastname: null,
}
});
这是来自ui-router repo的相关section。
答案 2 :(得分:0)
您的secondView
州应该是:
$stateProvider.state('secondView', {
url: '/second-view',
params: {
firstname: null,
lastname: null
},
templateUrl: './partials/view2.html',
controller: 'secondController'
});
那应该解决它。