Reputation: 3384
I am new to Angular world and struggling on how to controll the loading of partials. In my app on a changing the value of drop down I am getting the template url (the url of the partial I want to render) from server. Now using that template url I want to load that partial in my page. I know inserting a partial can be done using directives, but how do I change the template url in directive to load different partials? In simple word, I've change partial method in my controller which gets template url from server, and on ng-change event I am invoking this function, now how I use the template url to render partial in my targeted placeholder?
Upvotes: 2
Views: 2357
Reputation: 614
You could simply use the ng-include
directive to load a partial. You bind its value to a variable containing partial's URL. This variable can be bound to the the drop down list (or anything else). This way, if you select an item in the drop down list, the partial URL will be updated, thus loading the corresponding partial.
Have a look at the below snippet (or Plunkr, if you want to play with it yourself!), which does the same thing:
angular.module('app', [])
.controller("MainCtrl",
function() {
this.partialId = 1;
this.getPartialUrl = function() {
return 'partial' + this.partialId + '.html';
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/ng-template" id="partial1.html">
<h2>Partial 1</h2>
<p>Content loaded from FIRST partial</p>
</script>
<script type="text/ng-template" id="partial2.html">
<h2>Partial 2</h2>
<p>Content loaded from SECOND partial</p>
</script>
</head>
<body ng-controller="MainCtrl as Main">
<h1>Partials from dropdown</h1>
<select ng-model="Main.partialId">
<option value="1">Partial 1</option>
<option value="2">Partial 2</option>
</select>
<div ng-include="Main.getPartialUrl()"></div>
</body>
</html>
Upvotes: 9