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

时间:2013-08-13 15:54:40

标签: javascript angularjs

我想重新加载模板和连接的Controller而不使用$routeProvider,因为 我的路径结构不适合.when(...)。我想使用$location.path()来读取网址并设置所需的操作。

但是:如果URL的路径发生变化,模板不会自动更新,也不会重新加载控制器。

有没有办法说出这样的话?

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

2 个答案:

答案 0 :(得分:0)

我建议调查Angular UI路由器,这些路由器是由编写角度的人写的。它会让你过渡到不同的状态,这听起来就是你想要的。

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

答案 1 :(得分:0)

我的解决方案:不要使用路线!只需更新模板的变量,控制器就不需要更新(只需更新数据):

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);
    }

}]);

对于HTML:

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