簡體   English   中英

角度重載模板+控制器,不使用路線

[英]Angular reload Template + Controller without using Routes

我想不使用$routeProvider重新加載模板和連接的Controller,因為我的Path結構不適合.when(...) 我想使用$location.path()來讀取URL並設置所需的操作。

但是:如果URL的路徑更改,則模板不會自動更新,也不會重新加載控制器。

有沒有辦法這樣說?

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

我建議看看由編寫angular的同一個人編寫的Angular UI Router。 它會讓您過渡到不同的狀態,這聽起來像是您要嘗試做的事情。

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

我的解決方案:不要使用路線! 只需為模板更新變量,控制器就不需要更新(只需更新數據):

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM