How can I dynamically change the controller for ng-include
in AngularJS?
In my application, users can create content pages along with controllers. I am able to adjust the ng-include
source dynamically, but I am unsure of how to associate a new controller based on user selection. The code snippet below is not functioning as expected:
<div ng-app="MyApp">
<div ng-controller="ParentController">
<select ng-model="currentItem" ng-options="item as item.url for item in items track by item.url">
</select>
{{ currentItem }}
<div ng-include src="currentItem.url" ng-controller="currentItem.controller"></div>
</div>
</div>
The JavaScript code associated with this functionality is as follows:
var app = angular.module("MyApp",[]);
app.controller('ParentController', ['$scope',function($scope){
$scope.items = [{
url: 'page1.html',
controller: 'Page1Controller'
},
{
url: 'page2.html',
controller: 'Page2Controller'
}];
$scope.currentItem = {};
}]);
app.controller('Page1Controller', ['$scope',function(){
alert('Page1');
}]);
app.controller('Page2Controller', ['$scope',function(){
alert('Page2');
}]);