8

在我的应用程序中,主模板有一个月份的下拉列表(Jan, Feb ...)。

主模板包含一个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
}
4

3 回答 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
于 2013-09-09T04:22:41.757 回答
2

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

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

于 2013-09-09T03:46:56.797 回答
1

小提琴包括 http://jsfiddle.net/hzxNa/106/

小提琴在同一个“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 文件

于 2013-09-09T03:27:13.430 回答