AngularJS/ui-router:$ state.go在ng-click内不起作用

问题描述:

我在视图中有以下代码:

I have a view where I have the following code:

<input type="button" value="New Post" ng-click="$state.go('blog.new-post')">

目标是无需使用href即可过渡到新状态.不幸的是,上面的代码无法执行.

The goal is to transition to a new state without having to use href. Unfortunately the code above just does not fire.

我还尝试为此视图在控制器中包括$ state:

I also tried to include $state in the controller for this view:

app.controller('blogPostsController', function($scope, $stateParams, $http, $state) ...

但是仍然没有. transictionTo也似乎不起作用.

But still nothing. transictionTo also does not seem to work.

任何人对如何使这项工作有任何想法吗?

Anyone has any idea on how to make this work?

我只能通过分配以下内容才能使它起作用:

I could only make it work by assigning:

$scope.$state = $state;

在我的控制器内.这看起来很丑.如果没有将$ state分配给作用域,真的没有其他方法可以访问$ state吗?

inside my controller. This seems ugly. There is really no other way to access $state without assigning it to scope?

根据 https://github.com/angular-ui/ui-router/wiki/Quick-Reference#note-about-using-state-within-a-模板,您可以将其添加到$rootScope,这样它将在所有作用域中可用,因此在所有模板中都可用

According to https://github.com/angular-ui/ui-router/wiki/Quick-Reference#note-about-using-state-within-a-template you can add it to $rootScope, so it will be available in all the scopes and hence all the templates, by

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
  $rootScope.$state = $state;
  $rootScope.$stateParams = $stateParams;
});