1

I have a header view with his controller included in my page with:

<div ng-include="'header.html'" ></div>

the header includes an action call like save, update... I want when the user clicks in the header action update my main controller.

But I can't access and modify the main contoller $scope from ng-included page

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.value = 'first value';

});

app.controller('HeaderCtrl', function($scope) {
  $scope.header = 'from header';

  $scope.update = function(){
    $scope.$parent.value = 'new value';
  }
});

I've created a plunker demo to illustrate the issue

http://plnkr.co/edit/xeMD2NxUdb6g8CEcRnFu?p=preview

2 Answers 2

1

When updating a value from a parent scope in a child scope, I normally use one of these:

  1. Passing an object to the child and updating the propriety inside the object
  2. Passing a function to the child scope and calling this function to update the value.

In your example, if you use the option (1), it would be like this:

app.js file

app.controller('MainCtrl', function($scope) {
  $scope.value = {
    data: 'first value'
  };
});

app.controller('HeaderCtrl', function($scope) {
  $scope.header = 'from header';

  $scope.update = function(){
    $scope.$parent.value.data = 'new value';
  }
});

Not using ng-include, but you can take a look at this example passing function to a component to update data

For further understatement of the scopes in AngularJS, you can read What are the nuances of scope prototypal/prototypical inheritance in AngularJS?

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Had a lot of problems with this, go I am happy to help. If you are interested there is this Angular 1 Style Guide by John Papa. It is a nice read to write better code in AngularJS and he also explains why to do so.
1

In your specific case you could use:

$scope.$parent.$parent.value = 'new value';

Check the Modified plunkr.

But the real solution would be to use a designated property for each controller, or better yet use the controller as syntax.

Comments

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.