sagar chopada sagar chopada - 2 years ago 115
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


<!DOCTYPE html>
<html ng-app='MyApp'>
<title>ng-model can't update</title>
<meta charset="UTF8">
<script src=""></script>
<script type="text/javascript" src=""> </script>

<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>

Advance Thanks For Help.

Answer Source

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.


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('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() {
          ctrl.$render(); //to update $modelValue

Demo Plunkr

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download