如何重新加载AngularJS部分模板?

8
在我的应用程序中,主模板有一个月份下拉列表(1月、2月...)。
主模板包含一个使用routeProvider加载部分模板的ng-view
如何从主模板的控制器刷新ng-view(通过重新运行其控制器)?
这样,在用户切换到不同的月份时,部分模板内容将得到刷新。
主模板HTML:
....
<body class="" ng-controller="Main">
    <div ng-view></div>
</body>

路由提供者:

....
.config([ '$routeProvider', function($route) {
  $route.when('/module/:module', {
    templateUrl : 'partial/module.html',
    controller : Module
  }).otherwise({
    templateUrl : 'partial/dashboard.html',
    controller : Dashboard
  });
} ]);

主控制器:

function Main($scope, $cookies) {
    ...switch month and ajax...
    // Reload ng-view goes here
}

2
请分享您的JavaScript和HTML代码。 - ssilas777
1
我的答案中添加了fiddle:http://jsfiddle.net/hzxNa/106/ - Anton
3个回答

5

AngularJS广播功能在这里起作用...

主模板控制器:

$scope.switch_month = function(new_month) {
  $.ajax({
    ....
    success : function() {
      $scope.$broadcast("REFRESH");
    },
    ....
  });

};

每个部分模板控制器:

var refresh = function() {
  .... template initialization
};
refresh(); // initialize at once
$scope.$on("REFRESH", refresh); // re-initialize on signal

2
这与您最初的问题有何关联? - Anton
1
你不应该根据用户的选择重新运行控制器,你确定你应该朝着那个方向前进吗? - Anton
我的使用情况有点特殊,以下是更多细节:在切换到另一个月份时,API服务器状态会发生变化,并将提供与所选月份相关的内容,因此所有部分模板都需要重新初始化。 - user972946
1
这是一种不符合 Angular 规范的做法。应该通过 $http 或 $resource 将数据加载到模型/控制器中,并将模型/控制器绑定到部分,这样绑定的部分将自动刷新,而无需重新运行控制器。 - Anton
你不需要重新初始化任何东西。模板已经绑定并根据控制器中的数据自动更新。 - Anton
显示剩余4条评论

2

您不必担心重新加载模板。因为模板已经被加载,所以当您在Main控制器中更改数据时,局部模板中的双向数据绑定应该可以正常工作,因为模板在控制器的作用域内。

您可以使用$location.url('/module/:module')在需要重新加载视图时重新加载视图,因此控制器将被重新评估。


我很感激,但在我的使用情况下,切换月份会导致服务器状态改变,并且部分模板应该重新初始化自己(通过向服务器发出API调用)。 - user972946
1
@HowardGuo 好的。那么你可以尝试将这个代码放在回调函数中,当服务器状态成功时执行。$location.url('/module/:module'),并插入正确的模块参数。 - zs2020

1

包含fiddle

http://jsfiddle.net/hzxNa/106/

该fiddle中的模板与同一“html”文件中,但也可以将它们放入单独的文件中。

  <!-- template1.html -->
  <script type="text/ng-template" id="template1.html">
    Content of template1.html<br/>
    {{mydata}}
  </script>

  <!-- template2.html -->
  <script type="text/ng-template" id="template2.html">
      Content of template2.html<br/>
      {{mydata}}
  </script>


  <div ng-controller="Ctrl">
    <select ng-model="template" ng-options="t.name for t in templates">
    </select>
    url of the template: <tt>{{template.url}}</tt>
    <hr/>
    <div ng-include src="template.url"></div>
  </div>    

你可以使用ng-include并将其绑定到所需的模板。
<div ng-include src="template" ></div>

其中,template是您控制器中的变量,指向一个html文件,这个文件就是您的模板。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接