Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ng-init scope issues

I'm trying to use ng-include with ng-init to re-use the same component by only changing its data.

The component code ("slider.html", which has no controller) looks like this:

<div ng-repeat="person in persons">
     {{person.name}}
</div>

From the main view, I want to reuse the same component changing "persons" list so in the view I have:

<!--slider #1 -->
<div ng-init="persons=english" ng-include ="'inc/app/views/widgets/slider.html'"></div>

<!-- slider #2 -->
<div ng-init="persons=german" ng-include ="'inc/app/views/widgets/slider.html'"></div>

and in the controller I initialize the 2 lists "english" and "german" like this:

 $scope.english = records.filter(function(t){return t.nationality=="english";});
 $scope.german = records.filter(function(t){return t.nationality=="german";});

What happens is that the 2 components shows the same list of data (german); is there a way to bind the 2 different sets to the components?

like image 652
Dario Avatar asked Sep 30 '22 13:09

Dario


1 Answers

That (having both lists being set as German) happens because, at the end, you are only using one controller, which has only one scope in which the persons varaiable exists. When AngularJS starts its bootstrapping process, it processes the first ng-init, updating the current controller's persons variable to English. Then it processes the second ng-init, updating again the same persons variable now to German. Then, when the ng-repeat is rendered, it will take the current and unique persons variable data, hence, being everything in German.

What you can do is to have an independent controller per component (slider.html), so each controller will have its own binding variables so you can create a persons variable for each one and initialize every controller's variable independently with your ng-init directive. Example:

<div ng-controller="MySubController" ng-repeat="person in persons">
     {{person.name}}
</div>

...

<!--slider #1 -->
<div ng-init="initMySubController(english)" ng-include ="'inc/app/views/widgets/slider.html'"></div>

<!-- slider #2 -->
<div ng-init="initMySubController(german)" ng-include ="'inc/app/views/widgets/slider.html'"></div>

In a JS file:

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

myApp.controller('MySubController', ['$scope', function($scope) {
    $scope.persons = [];

    $scope.initMySubController = function(personsData) {
        $scope.persons = personsData;
    }
}]);
like image 89
Roberto Linares Avatar answered Oct 02 '22 14:10

Roberto Linares