Nicolas Schejtman
Nicolas Schejtman

Reputation: 433

How to read value of a field updated by ng-model in jQuery

HTML file

<input id="myName" ng-model="myName" val="{{myName}}">

Coffee Script file

$http.get('/api/name').then(
    (resp) ->
      $scope.myName = resp.data.name
      $('#myName').val() # this is still ""    
    ,
    (errorResp) ->
      # code
  )

As you can see from the code above I'm trying to get the value from my API and then adding it to the scope. I have an event binding in jQuery that every time the input value changes, it draws the name to a canvas. Thing is, when I bind resp.data.name to $scope.myName the .val() still returns "" as if the input haven't changed.

Upvotes: 1

Views: 1256

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

No need to use val="{{myName}}" in input element just use ng-model="myName" so no need use JQuery to set or get value. you can try using $timeout in your response if get data from response but input hasn't changed.

<input type="text" id="myName" ng-model="myName">

Coffee Script file

$http.get('/api/name').then(
    (resp) ->
      $scope.myName = resp.data.name    
    ,
    (errorResp) ->
      # code
  )

Upvotes: 0

fracz
fracz

Reputation: 21249

The value of input will be updated at the end of the current digest cycle. You can wait for it with a $timeout (inject it to your controller):

(resp) ->
  $scope.myName = resp.data.name
  $timeout ->
    $('#myName').val()

and HTML:

<input id="myName" ng-model="myName">

However, I strongly recommend you to read “Thinking in AngularJS” if I have a jQuery background and How does data binding work in AngularJS.

Upvotes: 1

Related Questions