【问题标题】:How to reload AngularJS partial template?如何重新加载 AngularJS 部分模板?
【发布时间】:2013-09-09 12:22:41
【问题描述】:

在我的应用中,主模板有一个月份(一月、二月...)的下拉列表。

主模板包含一个ng-view,使用routeProvider加载部分模板。

如何从主模板的控制器刷新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
}

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

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

【讨论】:

  • 这与您最初的问题有何关系?
  • 它“从主模板的控制器刷新 ng-view(通过重新运行其控制器)”。
  • 你不应该需要根据用户选择重新运行控制器,你确定你应该朝着那个方向前进吗?
  • 我的用例有点特殊,这里有更多细节:切换到另一个月份时,API 服务器状态会发生变化,并将提供与所选月份相关的内容,因此所有部分模板都需要重新初始化。
  • 这是一种不拘一格的做事方式。数据应通过 $http 或 $resource 加载并映射到您的模型/控制器,绑定到您的模型/控制器的部分将自动刷新,而无需您重新运行控制器。
【解决方案2】:

您不必担心重新加载模板。由于加载了模板,因此当您更改 Main 控制器中的数据时,部分模板中的 2 路数据绑定应该只工作,因为模板在控制器的范围内。

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

【讨论】:

  • 我很感激,但是在我的用例中,切换月份会导致服务器状态发生变化,并且部分模板应该重新初始化自身(通过对服务器进行 API 调用)。
  • @HowardGuo 好的。然后你可以尝试把这个放在成功建立服务器状态的回调函数中。 $location.url('/module/:module'),插入正确的模块参数
【解决方案3】:

包括小提琴 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>

其中模板是控制器中的变量,它指向作为模板的 html 文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 2013-10-05
    相关资源
    最近更新 更多