0

This plunker is from Angular ngOptions sample:

ngOption/Select Angular Sample

However, I added an ngIf to the first select resulting in:

<div ng-if="1<2">
    Color (null not allowed):
    <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
</div> 

Something interesting that you may notice is that the ngIf breaks the ngModel binding and nothing happens when you change your selection.

Because the same code without the ngIf produces the expected results.

Can you please confirm if this is a bug in angular, my code and/or if there is a work around it?

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
  • ng-if creates a child scope. I cannot see the plunker.. so exactly not sure if that is what the issue is. So you may be setting `myColor` in the child scope and trying to access it in the parent scope? Check this http://jsbin.com/namimimaqe/1/edit – PSL Oct 27 '14 at 20:52
  • Please read this: http://stackoverflow.com/questions/18128323/angularjs-if-you-are-not-using-a-dot-in-your-models-you-are-doing-it-wrong – Kate Miháliková Oct 27 '14 at 20:56
  • 2
    This is an awesome explanation.. https://github.com/angular/angular.js/wiki/Understanding-Scopes and http://stackoverflow.com/questions/14101099/ng-include-causes-the-controller-block-to-re-render/14104318#14104318 – PSL Oct 27 '14 at 21:02

2 Answers2

2

Using the ng-if directive creates a new scope for the DOM inside it. To reference the myColor variable on the parent scope, write ng-model="$parent.myColor"

<div ng-if="1<2">
    Color (null not allowed):
    <select ng-model="$parent.myColor" ng-options="color.name for color in colors"></select><br>
</div> 
user12121234
  • 2,519
  • 2
  • 25
  • 27
1

You can add $parent to your ng-options as ng-if creating child scope

please see below

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

app.controller('firstCtrl', function($scope) {
  $scope.colors = [{
    name: "red"
  }, {
    name: "black"
  }]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="firstCtrl">

    <div ng-if="1<2">
      Color (null not allowed):
      <select ng-model="myColor" ng-options="color.name for color in $parent.colors"></select>
      <br>
    </div>

  </div>
</body>

or use controller as syntax ie:

HTML:

<body ng-app="app">
  <div ng-controller="firstCtrl as vm ">

    <div ng-if="1<2">
      Color (null not allowed):
      <select ng-model="myColor" ng-options="color.name for color in vm.colors"></select>
      <br>
    </div>

  </div>
</body>

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

app.controller('firstCtrl', function() {

  var vm = this;
  vm.colors = [{
    name: "red"
  }, {
    name: "black"
  }]


});
sylwester
  • 16,498
  • 1
  • 25
  • 33
  • 3
    No no no `$parent`, it is bad... There are many other better ways to handle this. – PSL Oct 27 '14 at 20:56