changus
changus

Reputation: 763

AngularJS: binding to ng-repeat blurs the input inside the repeater

I have a similar problem to this one here: https://groups.google.com/forum/#!msg/angular/eB19TlFHFVE/Rlh--XImXeYJ

Here is the fiddle: http://jsfiddle.net/KGu9n/25/

My problem is that I also have a save function that gets called as the user is typing.

So I have something like this (where there may be manipulation to $scope.piece.movements in the backend. When the object comes back as response.data, it re-sets the $scope.piece.movements and it loses focus at that point.

$scope.save = function () {
$http.post('/save/', { object: $scope.piece.movements }).then(function (response) {
      $scope.piece.movements = response.data; // loses focus here
 });
};

Any help would be great! And if someone knows how I can simulate a post/save in fiddle/plnkr, I will gladly update my fiddle.

Upvotes: 0

Views: 255

Answers (1)

Paul Ryan
Paul Ryan

Reputation: 1509

Instead of using a function it would be preferable here to to use $watch for changes to pieces. Then in watch you can perform logic to determine if this is the right time (see timeout logic) to trigger changes and call out to a factory to perform the save. As shown here http://jsfiddle.net/xmltechgeek/HbDDf/ this works without loosing focus.

var app = angular.module('app', [])
    .controller('controller', function($scope, $timeout, dummy) {
        $scope.piece = {};
        $scope.piece.movements = [{name: "Allegro"} , {name: "Presto"}];

        var saveTimeout;
        $scope.$watch('piece.movements', function(){
            $timeout.cancel(saveTimeout)
            saveTimeout = $timeout(function(){
                dummy.save($scope.piece.movements, function(data){
                    $scope.piece.movements = data;
                    console.log($scope.piece.movements);
                })
            }, 1500);
        }, true);

    })
.factory('dummy', function(){
    var changes = {
        content: "",
        save: function(content, callback){
            this.content = content;
            callback(this.content);
        },
        get: function() {
            return this.content;
        }
    };
    return changes;
});

Upvotes: 1

Related Questions