AngularJS:将当前状态从视图传输到控制器
AngularJS: Transfer current state from view to controller
我正在使用 UI-Router
。我有一个视图,我需要在其中捕获它的当前状态并将其作为参数发送到控制器到按钮中的 ng-click
函数。
当我console.log
函数内的传输对象transferState
时,以下方法返回undefined
<button ng-click="transferState($state.current.name)">Click me</button>
我该怎么做?
您必须将 $state 传递给您的控制器或在 运行 阶段传递给 $rootscope。
然后您可以从您的视图中访问 $state。
例如:
angular.module('myApp').controller('myCtrl', function($scope, $state) {
$scope.$state = $state;
});
一种常见的方法是将两个频繁使用的服务注入 $rootScope
。这在示例应用程序中使用 - app.js
.run(['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.For example,
// <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
// to active whenever 'contacts.list' or one of its decendents is active.
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
现在,每个视图都可以直接访问这些。示例应用程序是 here.
我正在使用 UI-Router
。我有一个视图,我需要在其中捕获它的当前状态并将其作为参数发送到控制器到按钮中的 ng-click
函数。
当我console.log
函数内的传输对象transferState
undefined
<button ng-click="transferState($state.current.name)">Click me</button>
我该怎么做?
您必须将 $state 传递给您的控制器或在 运行 阶段传递给 $rootscope。 然后您可以从您的视图中访问 $state。
例如:
angular.module('myApp').controller('myCtrl', function($scope, $state) {
$scope.$state = $state;
});
一种常见的方法是将两个频繁使用的服务注入 $rootScope
。这在示例应用程序中使用 - app.js
.run(['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.For example,
// <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
// to active whenever 'contacts.list' or one of its decendents is active.
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
现在,每个视图都可以直接访问这些。示例应用程序是 here.