javascriptangularjsscopeprototypeangularjs-ng-include

modify main controller $scope from ng-include controller


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


Solution

  • 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?