AngularJS select ng change function without finding selected model

I am having problems with basic angular bindings.

my opinion:

<select ng-model="selectedPerson" ng-options="person.name for person in testdataset" ng-change="personChanged(selectedPerson)"> <option value="">All Persons</option> </select> 

my controller:

 $scope.testdataset = [ {name:"bill"}, {name:"bob"}, {name:"batman"} ]; $scope.personChanged = function(person) { console.log(person); } 

This works fine - the selected name is registered.

But it just prints "undefined" when the name is selected

View:

 <select ng-model="selectedPerson" ng-options="person.name for person in testdataset" ng-change="personChanged()"> <option value="">All Persons</option> </select> 

controller:

 $scope.testdataset = [ {name:"bill"}, {name:"bob"}, {name:"batman"} ]; $scope.personChanged = function() { console.log($scope.selectedPerson); } 

I'm new to angular and I'm just perplexed. I assume this is due to the $ scope "scope" inside the function, but I'm not sure how to troubleshoot ...

+6
source share
1 answer

This has already been mentioned in the comments, but your chosen member is a member of area A. Not necessarily a controller $scope ( $scope ). Depending on the rest of your page / application, selectedPerson may be in a different area. Suppose you use ng-repeat outside / above (as the parent for the displayed code), then selectedPerson will live as a member of this scope, not the scope of the controller.

The way the regions work is fairly simple, although it inherits from its parents. If you put something in the scope of the controller, this will be the largest area of ​​this controller (part of your html is labeled ng-controller ), if only you already enclosed this part inside another controller. Finally, there is $rootScope , which will have a real exclusive scope from which any other scope is inherited.

 <div ng-controller="MainController"> <div ng-repeat="item in items"> <!-- **This creates a new nested scope** --> <select ng-model="selectedPerson" ng-options="..."> </select> </div> </div> 

Using the above template, everything that you give $scope in your controller can be read both in the inner div and in the select itself. However, ng-model cannot be directly read in the controller.

If you do this in your controller:

 app.Controllers('MainController', function ($scope) { $scope.selectedPerson = {}; }); 

Then you will create an object in the outer scope, and your ng-model inherit and reference the same object. However, note that for each selection inside your ng-repeat , the MOST selectedPerson will be used.

Hope this explains why?

+2
source

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


All Articles