1

On Angular 1.3.x I made a select input that calls a function on ng-change. The surrounding has an ng-if statement.

html

<div class="form-group" ng-if="property">
  <label for="city-picker">in</label>
  <select class='form-control focus input-sm' ng-model="cityIds" ng-options="city.id as city.name for city in cities" ng-change="getMetrics(cityIds)">
    <option value="">all</option>
  </select>
</div>

controller

app.controller('MainCtrl', function($scope) {
  $scope.cities = [{
   name: "Amsterdam",
   id: 1
  },{ 
   name: "paris",
   id: 2
  }]
  $scope.property = true;
  $scope.getMetrics =  function(cityIds) {
    console.log(cityIds);
    console.log('$scope.cityIds is undefined: ', $scope.cityIds);
  }
});

When I change the select field the ng-change function is called with the correct $scope update, however, the $scope is not updated.

See the following plunker: http://plnkr.co/edit/sQaLts5xyGBjThjdQJwM

When I remove the ng-if statement the $scope is updated correctly by the select input. Could someone explain this behaviour?

Bunker
  • 1,040
  • 3
  • 12
  • 25
  • 1
    Here is explanation: http://stackoverflow.com/questions/30787147/angularjs-ng-if-and-scopes. It is always a good practice to have a `.` inside your ng-model path. – csharpfolk Jan 28 '16 at 17:54

1 Answers1

3

ng-if directive creates a new scope that prototypically inherits from the parent scope. So, your ng-model="cityIds" is updating cityIds in this new scope.

Use an object in the parent scope and refer to that from your ng-model.

For example:

in your controller, define

$scope.data = {cityIds: null};

and, refer to that from the template

ng-model="data.cityIds"

This ensure you are always dealing with parent scope's data.

Prashant
  • 7,340
  • 2
  • 25
  • 24
  • Or use 'controller as' syntax to give the controller a name and access the model through that. – Duncan Jan 28 '16 at 18:51