Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS update model from dom

Tags:

dom

angularjs

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
    });
});
like image 922
Jeremy Warne Avatar asked Feb 06 '13 22:02

Jeremy Warne


1 Answers

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.

like image 189
Mark Rajcok Avatar answered Nov 24 '22 22:11

Mark Rajcok