简体   繁体   中英

Angular.js two way data binding between two nested controllers

Im curious, is there a proper way that one should handle/implement 2 way data binding between 2 nested controllers. Let me explain the scenario.

I have a formController in which has some form elements. One of the form elements is a multiselect widget, for which i created a partial html that i can use in other places, and this partial runs with a separate Controller, lets calle it multiSelectController (note, this controller/partial/view is nested within the form/formController).

What i want is to be able to have the formController (which has the data), to pass in a list of "selected" items, like [1, 3, 7, 10] to the multiselect partial, which will then be able to render the widget with the correct items selected. And at the same time, when an item gets deselected or selected from the multiselect partial, i want to be able to pass the new selected list to the formController/scope (so i can display saying 1, 3, 5 are now selected).

So to simplify the question, i want to know what is the best/corerct way to pass in a model/variable to a child view/controller while retaining the databinding, thus the child view/controller can make changes to the said variable within it while it updates the parent.

The best way according to me is :

  1. Create a service, that will hold all the model variables.

     angular.service("dataService", function() { this.value1 = ""; this.value2 = ""; }); 
  2. reference that service in your controllers, saving their reference in the scope.

     angular.controller("myCntrl1", function($scope, dataService) { $scope.dataService = dataService; }); angular.controller("myCntrl2", function($scope, dataService) { $scope.dataService = dataService; }); 
  3. Now in your html, you refer all your modal variables using the service reference :

      // Controller 1 view <div ng-controller="myCntrl1"> <input type="text" ng-model="dataService.value1" /> </div> // Controller 2 view <div ng-controller="myCntrl2"> The value entered by user is {{dataService.value1}} </div> 

Since formController is a parent controller, you need not worry about accessing its model/varaibales, just add $parent in child's scope to access any parent property

$scope.$parent.someProperty

So, if you change or update this variable, it will automatically updated in parent's scope also.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM