简体   繁体   English

角度重载模板+控制器,不使用路线

[英]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(...) . 我想不使用$routeProvider重新加载模板和连接的Controller,因为我的Path结构不适合.when(...) I want to use $location.path() to read the URL and set the desired action. 我想使用$location.path()来读取URL并设置所需的操作。

But: if the path of the URL changes, the template doesn't automatically update and neither is the controller reloaded. 但是:如果URL的路径更改,则模板不会自动更新,也不会重新加载控制器。

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. 我建议看看由编写angular的同一个人编写的Angular UI Router。 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 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: 对于HTML:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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