Micky
Micky

Reputation: 737

ui-sref doesn't generate a href, despite of router conf and state in a $scope variable

I am having some problems in understanding where to find my mistake. I have a state stored in a $scope variable. Inspecting the page, I see that the right state is stored in the ui-sref property in the html..with a strange generated comment == $0 and another very curious behaviour is that if I hardcode the state name (so without keeping it from the scope variable), it works and I can obtain the href!

enter image description here

I have a ui-view in the html template, and the relative states:

.state('push', {
            url: "/push/:type",
            templateUrl: "firstday__push.do",
            controller: 'PushController'
})

and this is my controller:

(function (module) {
"use strict";
var HeaderController = function ($scope, $rootScope, $state) {
    console.log("Header Controller");
    $scope.previous = "";

    $scope.showBack = function () {
       if ($state.current.name !== 'home') {
            return true;
        }

        return false;
    };

    $scope.goTo = function (dest) {
        if(dest) {
            $state.go(dest);    
        } else {
            $state.go('home');
        }

    };

    $rootScope.$on("$stateChangeSuccess", function (ev, to, toParams, from, fromParams) {
        $scope.previous = from.name;
        console.log($scope.previous);
        console.log(from);
    });

    var nanobar = new Nanobar({
        classname : 'progress'
    });
};

module.controller("HeaderController", HeaderController);

}(angular.module("firstday_app")));

and in the template:

From the screenshot I can always see the correct values, so really don't know what's wrong in my code. Any idea?

Thanks in advance for your precious support!

Upvotes: 0

Views: 62

Answers (1)

chrisboustead
chrisboustead

Reputation: 1563

This is due to you trying to assign only the state name to the $scope.previous property. If that state name is something such as your push state, it will not be a valid state as push requires a type parameter for ui-sref to resole to a valid state:

ui-sref="push({type:'someType'})"

The better approach (assuming you always want to go to the previous state) may be to use a function to send the user back on click:

$scope.goPrevious = function(){
    // Make sure $window is injected in your controller.
    $window.history.back();
}

And your click diretive:

ng-click="goPrevious()"

Upvotes: 0

Related Questions