Débora
Débora

Reputation: 5952

Angularjs get the last or currently change model name

There can be different kind of input elements on the page. Assume, each element is bound to a model. Is there a way to get the currently changing or,last recent modified model name when any of input element's value is changed ? ( 'watch' can be used, but then it will be required to add each element to watch. I think of a way without watch assigned to each element: "A common listerner")

Upvotes: 2

Views: 627

Answers (1)

Thomas Roch
Thomas Roch

Reputation: 1216

If you have all your models under the same object, you can perform a deep watch on that object and build an history.

<input type="text" ng-model="user.name" />
<input type="text" ng-model="user.email" />
<input type="text" ng-model="user.details.phone" />

And a controller

function Controller($scope) {
    $scope.user = {
        details: {}
    };

    var lastValue;

    // Deep watch ('true' as last argument)
    $scope.$watch('user', function (newVal, oldVal) {
       // Add to history (create a copy)
       lastValue = angular.copy(oldVal);
    }, true);
}

If you are using Angular 1.3+

You can look at ngModelOptions https://docs.angularjs.org/api/ng/directive/ngModelOptions if you want better control over when a model is updated.

Additionally you can look at $rollbackViewValue() on the FormController and ngModelController: https://docs.angularjs.org/api/ng/type/form.FormController#$rollbackViewValue, https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$rollbackViewValue

Upvotes: 2

Related Questions