user972946
user972946

Reputation:

How to reload AngularJS partial template?

In my app, main template has a drop-down list of months (Jan, Feb ...).

The main template contains an ng-view, loaded with partial templates using routeProvider.

How do I refresh the ng-view (by re-running its controller) from main template's controller?

So that partial template content will refresh when user switches to a different month.

Main template HTML:

....
<body class="" ng-controller="Main">
    <div ng-view></div>
</body>

Route provider:

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

Main controller:

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

Upvotes: 8

Views: 42711

Answers (3)

user972946
user972946

Reputation:

AngularJS broadcast function works here...

Main template controller:

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

};

Each partial template controller:

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

Upvotes: 5

Anton
Anton

Reputation: 7719

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

The fiddle has the templates in the same 'html', but you can put them into separate files as well

  <!-- 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>    

you can use ng-include and bind it to the template you need

<div ng-include src="template" ></div>

where template is a variable in your controller that points to a html file which is your template

Upvotes: 1

zs2020
zs2020

Reputation: 54541

You should not worry about reloading the template. Since the template is loaded, the 2-way data binding in the partial template should just work whenever you change the data in the Main controller since the template is in the controller's scope.

You can use $location.url('/module/:module') to reload the view whenever you want, hence the controller will be re-evaluated.

Upvotes: 2

Related Questions