Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating model and binding update operations with UI

Tags:

angularjs

I currently have developed a table of content using AngularJS, the table will populate based on an Angular Service "Model" which invokes a web service and returns list and using ng-repeat and creating a table and all its content.

Everything at the moment works fine, I have a minor problem though. Part of the table, we are outputting an action button which when clicked invokes a web service which update the current record. Am trying to make the record data gets updated automatically, but i must refresh the page in order to see the changes.

Here is my code

My app.js

angular.module('my_vehicles', ['vehicleServices', 'AccountsDirectives']);

service.js

'use strict';

angular.module('vehicleServices', ['ngResource']).
    factory('Car', function($resource) {
        return $resource('/vehicle/api/car.json/:id', {},
            {
                query:   {method:'GET',     isArray:false},
                delete:  {method:'DELETE',  isArray:false},
                update:  {method:'PUT',     isArray:false}
            }
        );
});

controller.js

'use strict';

function MyVehicleController($scope, Car) {

    var init = function() {
        $scope.page_has_next = true;
        $scope.cars = [];
        $scope.page = 1;
    };

    // initialize values
    init();


    Car.query({my_vehicle: true},
        // success
        function(data) {
            $scope.page_has_next = data.has_next;
            $scope.cars = data.objects;
        },
        // error
        function(data) {

        }
    );


    $scope.mark_sold = function(id, index) {
        Car.update({
            id      : id,
            status  : 'S'
        },
        function(data) {

        });
    }

    $scope.delete = function(id, index) {
        Car.delete(
            {id: id},
            // on success
            function() {
                // remove the element from cars array and it will be
                // automatically updated by ng-repeat
                $scope.cars.splice(index, 1);
                $scope.loadMore(1);
            }
        );
    }

    $scope.is_total_zero = function() {
        return !!($scope.cars.length)
        //return $scope.cars.length > 0 ? true : false
    }


    $scope.loadMore = function(limit) {
        if($scope.page_has_next) {
            $scope.$broadcast('loading_started');
            console.log(limit);
            Car.query({my_vehicle: true, page: $scope.page, limit: limit},
                // success
                function(data) {
                    $scope.page_has_next = data.has_next;
                    $scope.cars = $scope.cars.concat(angular.fromJson(data.objects));
                    $scope.page++;
                    $scope.$broadcast('loading_ended');
                },
                // error
                function() {
                    $scope.page_has_next = false;
                    $scope.$broadcast('loading_ended');
                }
            );
        }
    }


    $scope.$on('loading_started', function() {
        $scope.state = 'loading';
    });

    $scope.$on('loading_ended', function() {
        $scope.state = 'ready';
    });


}

and finally, my html code

                    <tr ng-repeat="car in cars">
                        <td><a href="{% ng car.get_absolute_url %}">{% ng car._get_model_display.make_display %} {% ng car._get_model_display.model_display %} {% ng car._get_model_display.trim_display %}</a></td>
                        <td>{% ng car.created_at_format %}</td>
                        <td>{% ng car.view_count %}</td>
                        <td ng-model="car.status_label">{% ng car.status_label %}</td>
                        <td>
                            <div class="btn-group">
                                <button ng-disabled="car.status == 'S' || car.status == 'P'" ng-model="edit" class="btn btn-mini edit-btn">{% trans 'Edit' %}</button>
                                <button ng-disabled="car.status == 'S'" ng-click="delete(car.id, $index)" class="btn btn-mini delete-btn">{% trans 'Delete' %}</button>
                                <button ng-disabled="car.status == 'S' || car.status == 'P'" ng-click="mark_sold(car.id, $index)" class="btn btn-mini edit-btn">{% trans 'Mark as sold' %}</button>
                            </div>
                            </td>
                        </tr>

P.S the {% ng XXX %} is outputting {{ XXX }}, am using the above syntax because django templating engine does not allow me to use {{}} so i've developed a templatetag that would output {{}} ..

As mentioned earlier, my problem is that every time I invoke "mark as sold" it would invoke the cars.update() but it will not update the record displayed, must refresh to see changes. Any idea how i can solve this?

like image 497
Mo J. Mughrabi Avatar asked Nov 23 '12 12:11

Mo J. Mughrabi


2 Answers

As far as I understand your code you only update the db without updating the cars model ($scope.cars) so changes are only reflected in the db but not in the AngularJS application.

Maybe try the following:

$scope.mark_sold = function(id, index) {
    Car.update({
        id      : id,
        status  : 'S'
    },
    function(data) {
        $scope.cars[id].status = 'S';
    });
}
like image 147
F Lekschas Avatar answered Sep 19 '22 14:09

F Lekschas


You need to also update your in-memory cars array. You already have the array index (second parameter of the mark_sold function):

$scope.mark_sold = function(id, index) {
    Car.update({
        id      : id,
        status  : 'S'
    },
    function(data) {
        // Update in-memory array
        $scope.$apply(function(scope) {
          scope.cars[index].status = 'S';
        });

    });
}
like image 28
Andre Goncalves Avatar answered Sep 20 '22 14:09

Andre Goncalves