2

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.

2
  • My understanding is that the canonical approach would be to refactor the common controller code to a service, and invoke it from your controllers. I am somewhat new to angular but the things I've read suggest this is the "proper" way. Commented Sep 2, 2013 at 0:56
  • This should work. What is the problem there? Commented Sep 2, 2013 at 4:01

1 Answer 1

0

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I did this (as I explained in the question) but it doesn't work. scope variables of controller3 is not visible in inside <div ng-controller='controller3'> </div>
@Ali ng-include creates a child scope. scope variables of controller3 is definitely visible in the controller3. If you need to access the parent scope in view3, you need $parent variable to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.