sagar chopada sagar chopada - 5 months ago 40
AngularJS Question

ng-model is not updated, i used javascript library for change language in angularjs

ng-model cant't update untill i press space or back space..

I think this problem arrived because of i use third party library for changing language.

my laguage changing library is http://techhive.co.in/angular_language.js



angular.module("MyApp",[])
.controller("MyCtrl",function($scope,$http,$timeout){
changeLanguage('pramukhindic:gujarati');
});

<!DOCTYPE html>
<html ng-app='MyApp'>
<head>
<title>ng-model can't update</title>
<meta charset="UTF8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript" src="http://techhive.co.in/angular_language.js"> </script>

</head>
<body >
<div >
<div ng-controller='MyCtrl'>
<h3>ng-model not update untill we press space or backspace.</h3>
<form name="main_member_form">
<input id="tags" ng-model="test"/>
<label ng-bind="test"></label>
</form>
</div>
</div>
</body>
</html>





Advance Thanks For Help.

Answer

As you are updating angular context from 3rd party library, for those changes angular digest system doesn't aware of those changes. So even if outside world has change something that wouldn't updated angular scope binding on view, unless you run digest cycle.

Here in this case you are modifying context from event which is outside of angular context. For getting binding updated you need to run kick off digest cycle manually to see the changes on page using scope.$apply()/$timeout

$elem.on('focus', function () {
    //do add $timeout dependency over directive DI array.
    $timeout(function(){
       changeLanguage('pramukhindic:gujarati');
    })
});

Update

OP has changed whole code to have method in controller itself.

I'd love to suggest you to stick with directive approach to it, so that you could have you can handle over each input field individually by having single directive. 3rd party plugin is internally updating DOM value property of input field, rather than updating ng-model value. In this case what you need to do is, you need to set keyup handle over input to listen to onkeyup event. And the do apply digest cycle using $apply, thereafter set the value present inside a DOM to ng-model would work

Directive

.directive('myLang', function($parse, $timeout) {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      var model = $parse(attrs.ngModel).assign;
      console.log("Inside directive")
      element.on('keyup', function() {
        //upadate value of ngModel with value attached to DOM value attribute
        scope.$apply(function() {
          console.log(element.val())
          ctrl.$setViewValue(element.val());
          ctrl.$render(); //to update $modelValue
        });
      })
    }
  }
})

Demo Plunkr

Comments