Numerous problems with the ng-init scope

I am trying to use ng-include with ng-init to reuse the same component, only modifying its data.

The component code ("slider.html", which does not have a controller) is as follows:

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

In the main view, I want to reuse the same component that changes the list of "faces", 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 2 lists of "English" and "German" as follows:

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

What happens is that 2 components show the same data list (German); is there any way to associate 2 different sets with components?

+5
source share
1 answer

This (indicating both lists as German) is because in the end you use only one controller, which has only one area in which persons varaiable exists. When AngularJS starts its boot process, it processes the first ng-init, updating the current controller controller variable to English . Then it processes the second ng-init, again updating the same persons variable to German . Then, when rendering ng-repeat, it will accept the current and unique variables persons , therefore, everything will be in German.

What you can do is to have an independent controller for one component (slider.html), so each controller will have its own binding variables so that you can create a face variable for each of them and initialize each controller variable regardless of your ng-init . 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 the JS file:

 var myApp = angular.module('myApp',[]); myApp.controller('MySubController', ['$scope', function($scope) { $scope.persons = []; $scope.initMySubController = function(personsData) { $scope.persons = personsData; } }]); 
+4
source

Source: https://habr.com/ru/post/1205623/


All Articles