Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS / ui-router: $state.go does not work inside 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')">

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

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

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

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

Anyone has any idea on how to make this work?

EDIT: I could only make it work by assigning:

$scope.$state = $state;

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

like image 319
SrgHartman Avatar asked Dec 17 '13 15:12

SrgHartman


2 Answers

If you are using ui-router there is an attribute called ui-sref that can be used as follows:

<a ui-sref="blog.new-post"></a>

I recommend using that and styling the link as a button (can easily be done if you're using a CSS library like Twitter Bootstrap). Then you don't need to mess around with any JavaScript when writing your links.

If you need to pass a parameter into the state, you can do the following:

<a ui-sref="blog.edit-post({id: item.id})"></a>

where $scope.item is an object with an ID property you want to be passed as a URL parameter.

like image 72
jkjustjoshing Avatar answered Oct 21 '22 01:10

jkjustjoshing


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;
});
like image 35
Michal Charemza Avatar answered Oct 21 '22 03:10

Michal Charemza