francoleung
francoleung

Reputation: 257

Is it possible to change ng-model value without ng-change function?

Is it possible to change ng-model value without ng-change function?? The following method is not work

<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input id="checkbox" type="checkbox" ng-model="field">
 <div> {{field}} </div> 
</div></div>    

<script>
var myapp = angular.module('myApp', []);
myapp.controller('MyCtrl', function($scope){

if(document.getElementById("checkbox").checked){
$scope.field="YES";    

    }})

but use the following code is work for me

<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input id="checkbox" type="checkbox" ng-model="field" ng-change="change_text()">

<div>{{field}}</div> 

  <script>
    var myapp = angular.module('myApp', []);
    myapp.controller('MyCtrl', function($scope){

    $scope.change_text = function() {  
    $scope.field="YES";        
    }})
  </script>

Upvotes: 1

Views: 664

Answers (1)

Claies
Claies

Reputation: 22323

To accomplish what you are trying to do, you can use ng-true-value and ng-false-value to have your model be a type other than a boolean without breaking the two way data binding with ng-model.

for example:

<input id="checkbox" type="checkbox" ng-model="field" ng-true-value="'YES'" ng-false-value="'NO'">
{{field}}

Pass the values for ng-true-value and ng-false-value as string literals (wrapped in the extra quotes).

http://plnkr.co/edit/hjuwOV6q6iZOaXv89M6x?p=preview

Upvotes: 3

Related Questions