Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs: how to restart controllers to update the data source model to watch?

how to tell angularjs to stop watching an expired data object and force controllers to restart to look at a new model instance ?

    var ang = angular.module('ang', []);

    ang.controller('userCtrl', function($scope) {
        $scope.userData = myProject.getUserData(); // an OOP js data tree
    } 

    angular.bootstrap(document, ['ang']);

    // ... 

    myProject.reloadUserData(); // userData now a new instance

Angular works perfectly until I destroy the user data object to create a new data object instance.

How to tell angular to stop watching the old user data and start looking the new ? Basically I want to restart angular or the controllers.

like image 207
John Avatar asked Dec 11 '25 11:12

John


1 Answers

There's no need to restart your angular app just because the model updated. Not only is that round-about, but you'll have to take the performance hit of re-compiling the DOM.

Instead, I would suggest you create a service to handle the synchronization.

ang.factory('userService', function ($rootScope) {
    var userService = {
        // We'll initialize this in a moment
        data: undefined,

        // Method to refresh the data property
        refresh: function () {
            userService.data = myProject.getUserData();
        }
    };

    userService.refresh();

    return userService;
});

Now, in your controller, you'll use this service rather than the global myProject object.

ang.controller('userCtrl', function($scope, userService) {
    $scope.user = userService; // Bind to {{user.data}} in your templates
});

Finally, whenever you call myProject.reloadUserData(), you have to refresh the userService object.

$(document.body).injector().invoke(function (userService) {
    userService.refresh();
});

You may just want to add that to the method.

like image 183
Chris Bouchard Avatar answered Dec 14 '25 02:12

Chris Bouchard