ng-repeat not updating the list when adding data

前端 未结 3 613
余生分开走
余生分开走 2021-01-23 02:51

my problem is that the ng-repeat is not updating automatically the data. When I press add pin in my code, the element is added correctly to the database. If I reload the page th

3条回答
  •  萌比男神i
    2021-01-23 03:40

    Cannot agree with Gavin. First, what you're doing is totally fine. Creating instance of controller is a much better practice than using $scope. Second, $apply() is not needed here.

    The problem is ng-repeat created a new scope. While pin is updated, app.pins is not. You should do

    var app = angular.module("app", []);
    
    app.controller("AppCtrl", function ($http) {
    var app = this;
    
    $http.get("/api/pin").success(function (data) {
        app.pins = data.objects;
    })
    
    app.addPin = function (scope) {
        $http.post("/api/pin", {"title":"new", "image":"http://placekitten.com/200/200/?image=" + app.pins.length})
            .success(function(data) {
                add.pins.push(data);
            })
    }
    
    app.deletePin = function (index) {
        $http.delete("/api/pin/" + app.pins[index].id).success(function(response) {
                app.pins.splice(index, 1)
            })
    }
    
    app.updatePin = function (index) {
        $http.put("/api/pin/" + app.pins[index].id, app.pins[index]);
    }
    
    })
    

    and

    
    
    Pin Clone
    
    
    
    
    
    
    
    

    check here: How to update ng-model on event click using $event in Angularjs

提交回复
热议问题