I have two separate views (named view1.html and view.html) with separate controllers (named controller1 and controller2) and they are routed using config:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/view1', {templateUrl: 'view1.html', controller: controller1}).
when('/view2', {templateUrl: 'view2.html', controller: controller2}).
otherwise({redirectTo: '/view1'});
}]);
view1 and view2 have a shared part of template code, so I extracted it into a new template view (named view3.html) and use ng-include in view1.html and view2.html:
<span ng-view="">
...
<span ng-include="'view3.html'"></span>
....
</span>
also view3.html logic is independent from the controller1 and controller2, so the scope variables needed in veiw3.html is repeated in both of the controllers:
function controller1($scope){
...
some code to calculate $scope variables for view3
...
}
function controller2($scope){
...
same code to calculate $scope variables for view3
...
}
My question: is there any way to extract repeated codes in controllers into a separate controller for view3? I add ng-controller for view3 but it doesn't work:
<span ng-controller="controller3">
view3.html template codes here
</span>
I guess it's because view3.html is included in an element with ng-view directive and can not have a separate controller.
I think you can use ng-include
to achieve it:
In view1.html
<div ng-include src="'view3.html'"></div>
//other template for view1
In view2.html
<div ng-include src="'view3.html'"></div>
//other template for view2
In view3.html
<div ng-controller='controller3'>
//template for view3
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.