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

Sébastien
  • 11,860
  • 11
  • 58
  • 78
Med
  • 117
  • 1
  • 14

2 Answers2

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.

Sébastien
  • 11,860
  • 11
  • 58
  • 78
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?

Wesley Shann
  • 63
  • 3
  • 7
  • 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](https://github.com/johnpapa/angular-styleguide/tree/master/a1) by John Papa. It is a nice read to write better code in AngularJS and he also explains why to do so. – Wesley Shann Feb 10 '18 at 12:40