7

I've seen heaps of questions about this, and all of them seem to be solved by either calling $scope.$apply(), $scope.$digest(), or by triggering the change() method on the input. But I can't seem to get it working with any of those methods. In this fiddle, I can type a name into the box and get the model value to update as I type. But when I click the link, to set the input name to a certain value, I want the model name to update. What do I need to do?

The reason I'm trying to do this is I want to be able to refresh my angular model when a user autofills the form, using the browser autofill or LastPass or similar. Surely there's some angular command to refresh the model from the DOM?

http://jsfiddle.net/PXCUq/

$(function () {
    $('#setFirstName').click(function () {
        $('input.firstname').val('Test Name');
        angular.element($('input.firstname')[0]).scope().$apply();
        // Model still not updated
    });
});
2
  • Is there a reason you are not doing it this way instead?: <a ng-click="input.firstname = 'Test Name'">set first name</a>? Commented Feb 6, 2013 at 22:18
  • I'm looking for a workaround to make browser form autofills work. This is a simpler way of getting the value to change without user input, to demonstrate the problem. Commented Feb 6, 2013 at 22:29

1 Answer 1

6

Get the scope, then change the ng-model property:

$('#setFirstName').click(function() {
    var scope = angular.element($('input').get(0)).scope()
    scope.firstname = 'Test Name';
    scope.$apply();
});

You can come up with a better jQuery selector. I was only focusing on the Angular part.

Fiddle.

Sign up to request clarification or add additional context in comments.

2 Comments

This would sort of work... So to refresh the model from the dom, I'd need to run through every element, get its ng-model attribute, and set the model value like that. Is there really no way to do this within Angular?
You don't need to go through every element to get its scope. You just get scope once. Like: scope = angular.element($('div[ng-view] > *)[0]).scope()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.