简体   繁体   中英

Angular reload Template + Controller without using Routes

I want to reload a template and the connected Controller without using $routeProvider , because my Path-structure doesn't fit with .when(...) . I want to use $location.path() to read the URL and set the desired action.

But: if the path of the URL changes, the template doesn't automatically update and neither is the controller reloaded.

Is there a way to say something like this?

angular.module('myApp').controller('ctrl').reload()

I would suggest looking into the Angular UI Router written by the same guys who wrote angular. It will let you transition to different states which is what it sounds like you are trying to do.

https://github.com/angular-ui/ui-router

My solution: don't use Routes! Simply update a variable for your template, controllers don't need updates (simply update the data):

angular.module('myApp',[])

  .run(['$rootScope', '$location', 'myService', function ($rootScope, $location, myService) {

    $rootScope.view = "";

    // Some function to read the URL
    $rootScope.setRouting = function(){
      var p = $location.path().split("/");
      // Do things with p[0], p[1], ...
      // e.g. if url is /post/123
      $rootScope.view = p[0];
      myService.setData(p[1]);
    }

    // Monitor Location changes:
    $rootScope.$on('$locationChangeSuccess', function(event) {
      $rootScope.setRouting();
    });

    // And this is useful for calling within template: ng-click="go('...')"
    $rootScope.go = function(path){
      $location.path(path);
    }

}]);

And for the HTML:

<body>
  <ng-include src="view + '.html'"></ng-include>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM