L
L
leo_fr2015-12-19 14:00:50
symfony
leo_fr, 2015-12-19 14:00:50

Angularjs - Why didn't ng-repeat update?

I use symfony2 and angularjs in conjunction.
More about the problem, I have the task of making a regular CRUD application , everything works, but if I perform any actions, then my view is not updated ( for example, I have a user or I want to create a user, to see the result I need to refresh the page ). I have been sitting on the problem for more than a day, maybe I made a mistake somewhere and I don’t see it =) The results of my searches led me to the fact that I most likely have problems with the scope. Found an article about $scope.apply, but there was a problem with the fact that it knocks out a cycle error (or I don’t apply it correctly) and, as I understand it, this problem is usually connected with the fact that when we create our own directives, they are usually not visible. In general, I'm a little confused, I will be very glad if someone can help solve this problem. Maybe a problem with promises. Code description:
Controller in symfony2

/**
     * @Route("/edit", name="edit")
     */

    public function editAction (Request $request)
    {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $data = json_decode($request->getContent(),true);

            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('AppBundle:User')->find($request->get('userId', 'userName'));

            if (!$user) {
                throw $this->createNotFoundException(
                    'No user found id'
                );
            }

            $user->setName($data['userName']);
            $user->setAge($data['userAge']);
            $em->flush();

        }

        return new Response( json_encode(
                array('success' => 'Success' )

                )
            );
    }

Angularjs controller:
'use strict';

angular.module('prApp')
    .controller('tableCtrl', ['$scope','$rootScope', 'TableService', '$modal',
        function ($scope,$rootScope, TableService, $modal) {

            $scope.items = TableService.userTableInfo.infoTab();
            var items;
            $scope.new = {
                'name': '',
                'age': ''
            };

            $scope.eEdit = function (item) {

                var modalInstance = $modal.open({
                    templateUrl: 'editModalContent.html',
                    controller: 'editModalInstanceCtrl',
                    item : item,
                    resolve: {
                        item: function () {
                            return item;
                        }

                    }
                })
            };
      }
    ])

    .controller('editModalInstanceCtrl', function ($scope,TableService, $modalInstance, item) {
        $scope.item = item;
        $scope.temp = {id: item.id, name: item.name, age: item.age};
        $scope.eEditEnd = function (temp, item) {
            TableService.userTableEdit.editUserTable({id: $scope.temp.id,userName: $scope.temp.name, userAge: $scope.temp.age});

            $modalInstance.close();
        };
        $scope.cancel = function () {
            console.log('ng-click = cancel');
            $modalInstance.dismiss('cancel');
        };
    })

Angularjs factory (note editing happens via POST method, not PUT ) :
'use strict';

angular.module('prApp')
    .factory('TableService', function ($resource){
       var factory = {
           userTableEdit: $resource('/edit', {},{
               editUserTable:{method: 'POST', params:{userId: '@id'}}
           }),
         } ;
        return factory;
    });

Modal windows:
<!-- модальное окна редактирование -->

        <div>
            <script type="text/ng-template" id="editModalContent.html">
                <form data-ng-submit="editUserTab()">
                    <div class="modal-header">
                        <h4 class="modal-title">Редактировать пользователя</h4>
                    </div>
                    <div class="modal-body">
                        <p>Форма для редактирования данных</p>

                        <td>Name
                            <input
                                    class="form-control"
                                    data-ng-model="temp.name"/>
                        </td>
                        <td>Age
                            <input
                                    class="form-control"
                                    data-ng-model="temp.age"/>
                        </td>
                        <!--<td>Name<input class="form-control" value="{{item.name}}" data-ng-model="item.team.name"/></td>-->
                        <!--<td>Age<input class="form-control" value="{{item.age}}" data-ng-model="item.team.age" /></td>-->

                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-primary" type="submit" data-ng-click="eEditEnd(temp, item)">Save
                            changes
                        </button>
                        <button class="btn btn-default" data-ng-click="cancel()">Cancel</button>
                    </div>
                </form>
            </script>
        </div>

UI
Get the collection from the database
878c58189f704ed0ba85d7feb43786a1.pngScope $scope
49250969afa64da3a3c988027da85156.pngCall the modal window
7ae3af2a4a21459a95b2f2bab5f10608.pngMake changes
15d03ac29b6446c185183a01cc5ad6b5.pngResult after clicking on ng-click
92469b1f6aa148afaf9630fd8c958004.png How the scope changed when the modal window was called
6e4ce87aee314778992c18111dc5c7fb.pngThe result is displayed after we refresh the page:
5f36c8d9048442bc96a36cc069f114a3.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2015-12-19
@leo_fr

Um, i.e. do you want some magic to happen and update the data? There is no magic in Angular - if something happens, it's only because you need it.
You didn't write the main thing - the table template. I can assume that you are displaying data from the $scope.items array. The elements of this array are mapped to row elements of the table, in turn, each element of the array is mapped to the data in the row. If you make $scope.items[0].age = 20, then that 20 will appear in your table.
Now let's see what happens when you open the modal - you create a new JS temp object, copying the element values ​​from $scope.items into it.
All changes that you make to this temp with ng-model remain only in this object, it is not associated with anything (I think you did this so that uncommitted changes are not saved, that's ok). Further, your save just sends a request to the server, without distributing information about the changed object anywhere else. Therefore, the contents of $scope.items remain unchanged. The minimum working option, so that you don’t hammer your head now, is to do something like

$scope.eEditEnd = function (temp, item) {
            TableService.userTableEdit.editUserTable({id: $scope.temp.id,userName: $scope.temp.name, userAge: $scope.temp.age});
            angular.extend(item, temp);
            $modalInstance.close();
        };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question