Search code examples
javascriptangularjsangularjs-scopeangular-ui-routerangularjs-service

Angular js service value does not updates in the view


I'm using the stateProvider, and when the state is changed i want to update my breadcrumbs in the header. Instead of writing for each state its own embedded view, i just put on the service that shares the array of breadcrumbs with their names and links, when some state is being called function inside of each controller sets its own value of this array, i can see in the debugger how the value inside the service is being updated, but the view is not refreshed is there any suggestions? Code: Header controller:

$scope.breadcrumbs = breadcrumbsService.breadcrumbs;

The view:

<md-button ng-repeat="breadcrumb in breadcrumbs" ui-sref="{{breadcrumb.link}}"> {{breadcrumb.title}} </md-button>

Service:

.service("breadcrumbsService", function Breadcrumbs() {
        var self = this;
        self.breadcrumbs = [
            {title: "Home", link: "KeyStyle.home"}
        ];
    });

Any other controller code:

 .controller("ownerRegistrationController", ["$scope", "Owner", "$http", "domain", "breadcrumbsService",
        function ($scope, Owner, $http, domain, breadcrumbsService) {

            updateBreadcrumbs();
...
        function updateBreadcrumbs() {
                breadcrumbsService.breadcrumbs = [
                    {title: "Home", link: "KeyStyle.home"},
                    {title: "New owner", link: "KeyStyle.home.owner.registration"}
                ];
            }

Solution

  • When you re-assign breadcrumbsService.breadcrumbs, you are breaking the reference established in $scope.breadcrumbs = breadcrumbsService.breadcrumbs;

    Instead, you should push new entries on to the array. It should also trigger a digest cycle ($scope.$apply()) or be run on the next one ($scope.$applyAsync)

    function updateBreadcrumbs() {
        $scope.$applyAsync(function() {
            breadcrumbsService.breadcrumbs.push({
                {title: "New owner", link: "KeyStyle.home.owner.registration"}
            });
        });
    }