1

Very simple code:

    <div ui-if="showMemberId">
        <input ng-model="memberId" ng-change="test()" id="memberId" name="memberId" class="text" type="text">
    </div>

With this for the controller:

$scope.memberId = 'SDF';
$scope.test = function test(){
    console.log($scope.memberId);
};
$scope.showMemberId = true;

Bizarrely, the ng-change works but not the ng-model. When I type into the input, it just logs the string SDF to the console over and over because the model isn't changing.

Any ideas?

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • `ui-if` is one of many directives that create a new scope, and because your `ng-model` is a primitive, it won't be accessible in the way an object would be. This is an example of one of the most commonly encountered issues in angular, which is always solved with the "always use a dot" rule. – Claies Oct 18 '15 at 20:47
  • 1
    golden rule in angular is always use an object in `ng-model` so you don't break bindings on primitives – charlietfl Oct 18 '15 at 20:47
  • further reading: http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs – Claies Oct 18 '15 at 20:48
  • also, unless my facts are wrong, `ui-if` was removed from more current versions of the framework. – Claies Oct 18 '15 at 20:51

1 Answers1

2

Seems like ui-if is creating a child scope like ng-if does. So the outer memberId scope will be different than ng-model present inside the ui-if. In such cases you need to follow the dot rule while defining ng-model. Basically when it creates a child scope, its protypically inherited from parent scope. And prototypal inheritance works on object type not on primitive types

To make it working you need to define object inside controller like $scope.model ={} & define all the property in it .

Markup

<div ui-if="showMemberId">
    <input ng-model="model.memberId" ng-change="test()" 
     id="memberId" name="memberId" class="text" type="text"/>
</div>

Controller

$scope.model = {}; //made an object type model

I'd encourage you to use ng-if instead of ui-if, as angular does provide the same functionality.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299