webdad3
webdad3

Reputation: 9080

pre-populating fields, angularjs controller doesn't recognize the values

I am pre-populating fields from the Facebook API:

$("#inputParentName").val(response.name);
$("#inputParentEmail").val(response.email);
$("#inputParentBirthday").val(response.birthday);

In my AngularJS service I have the following function:

vm.addParent = function () {
    alert(vm.inputParentName);
    alert(vm.inputParentBirthday);
    alert(vm.inputParentEmail);

When this function gets called the pre-populated fields display as 'undefined' in the alert boxes. However if I type in the values I get the actual text that was typed in.

What do I need to do, to have my AngularJS code recognize the pre-populated values?

Upvotes: 0

Views: 1464

Answers (2)

tuckerjt07
tuckerjt07

Reputation: 922

To further clarify the reason that your values are not assigned to the model is that Angular has no clue they are present. Updating a field through a query element rather than ngModel bypasses Angular's data binding. Either calling for a $scope . digest after or placing the assignments into a $scope.$apply(function () {}) would work but is not recommended. Do as suggested and set the values with the built in models.

Upvotes: 1

Sina Khelil
Sina Khelil

Reputation: 1991

You are using jQuery to populate input field. What you should be doing instead is populating your angular scope value assigned to the ng-model of your input field

i.e.

<input type="text" name"inputParentName" id="inputParentName" ng-model="vm.inputParentName">
<input type="text" name"inputParentEmail" id="inputParentEmail" ng-model="vm.inputParentEmail">
<input type="text" name"inputParentBirthday" id="inputParentBirthday" ng-model="vm.inputParentBirthday">

should be populated not by using jQuery but by assigning the value using angular's scope. (this code likely goes in your controller)

$scope.vm = {
  'inputParentName': response.name,
  'inputParentEmail': response.email,
  'inputParentBirthday': response.birthday
}

Then the values will show up where intended....

(I am guessing at your html and javascript, but this is an approximate guess)

Do yourself a favor and avoid trying to marry jQuery and Angular - it can be done, but it is not necessary.

Upvotes: 1

Related Questions