最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why Ng Repeat is not working if button invoked from a different form? - Stack Overflow

programmeradmin2浏览0评论

I have a html table that contains an ng repeat directive and two button.The first one will open a modal that contains a new form and let me create my user and then when i click save it will add it to the list.The second one is in the same original form and do the add a user.

What i did not understand why when i click on the first button which is in a different form i can not update the ng repeat however for the second one it's possible. This is the code:

homepage.jsp

<body ng-app="myApp">
    <div class="generic-container" ng-controller="UserController as ctrl">
        <div id="createUserContent.jsp" ng-include="createUserContent"></div>
        <table>
            <tr>
                <td>
                    <button type="button" class="btn btn-primary"
                    ng-click="ctrl.openCreateUser()">Create</button>
                </td>
            </tr>
        </table>
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>ID.</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Email</th>
                    <th width="20%"></th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="u in ctrl.users">
                    <td><span ng-bind="u.ssoId"></span></td>
                    <td><span ng-bind="u.firstName"></span></td>
                    <td><span ng-bind="u.lastName"></span></td>
                    <td><span ng-bind="u.email"></span></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

user_controller.js

'use strict';

App.controller('UserController', function ($scope, UserService, $window, $log, $uibModalStack,
        $uibModal, $rootScope) {
    var self = this;

    self.users = [];

    self.fetchAllUsers = function () {
        console.log('----------Start Printing users----------');
        for (var i = 0; i < self.users.length; i++) {
            console.log('FirstName ' + self.users[i].firstName);
        }
    };
        /**
    this function will not work
    **/
    self.saveUser = function (user) {
        self.users.push(user);
        self.fetchAllUsers();
        $log.log("saving user");
        $uibModalStack.dismissAll();
    };

    /**
    this function works fine
    **/
    self.addNewRow = function () {
        var specialUser = {
                id : 12,
                firstName : 'john',
                lastName: 'travolta',
                homeAddress : {location:'chicago'},
                email : '[email protected]'
        };
        self.users.push(specialUser);
        $log.log("saving specialUser");
    };
    self.openCreateUser = function () {

        var modalInstance = $uibModal.open({
                animation : true,
                templateUrl : 'createUserContent',
                controller : 'UserController',
                resolve : {
                    items : function () {
                        return $scope.items;
                    }
                }
            });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    self.fetchAllUsers();
});

createUserContent.jsp

<form role="form" ng-controller="UserController as ctrl" >
    <div class="form-group">
        <label for="FirstName">FirstName</label> <input type="FirstName"
            ng-model="ctrl.user.firstName" class="form-control"
            id="FirstName" placeholder="Enter FirstName" /> <label
            for="lastName">lastName</label> <input type="lastName"
            class="form-control" id="lastName"
            ng-model="ctrl.user.lastName" placeholder="Enter lastName" />
        <label for="email">Email address</label> <input type="email"
            ng-model="ctrl.user.email" class="form-control" id="email"
            placeholder="Enter email" />
    </div>
    <div class="form-group">
        <label for="homeAddressLocation">Home Address</label> <input class="form-control"
            ng-model="ctrl.user.homeAddress.location" id="homeAddressLocation"
            placeholder="homeAddressLocation" />
    </div>
    <div class="form-group">
        <label for="SSOId">SSOId</label> <input class="form-control"
            ng-model="ctrl.user.ssoId" id="SSOId" placeholder="SSOId" />
    </div>
    <button type="submit" class="btn btn-default"
        ng-click="ctrl.saveUser(ctrl.user)">Save</button>
    <button type="submit" class="btn btn-default">Cancel</button>
</form>

I have a html table that contains an ng repeat directive and two button.The first one will open a modal that contains a new form and let me create my user and then when i click save it will add it to the list.The second one is in the same original form and do the add a user.

What i did not understand why when i click on the first button which is in a different form i can not update the ng repeat however for the second one it's possible. This is the code:

homepage.jsp

<body ng-app="myApp">
    <div class="generic-container" ng-controller="UserController as ctrl">
        <div id="createUserContent.jsp" ng-include="createUserContent"></div>
        <table>
            <tr>
                <td>
                    <button type="button" class="btn btn-primary"
                    ng-click="ctrl.openCreateUser()">Create</button>
                </td>
            </tr>
        </table>
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>ID.</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Email</th>
                    <th width="20%"></th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="u in ctrl.users">
                    <td><span ng-bind="u.ssoId"></span></td>
                    <td><span ng-bind="u.firstName"></span></td>
                    <td><span ng-bind="u.lastName"></span></td>
                    <td><span ng-bind="u.email"></span></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

user_controller.js

'use strict';

App.controller('UserController', function ($scope, UserService, $window, $log, $uibModalStack,
        $uibModal, $rootScope) {
    var self = this;

    self.users = [];

    self.fetchAllUsers = function () {
        console.log('----------Start Printing users----------');
        for (var i = 0; i < self.users.length; i++) {
            console.log('FirstName ' + self.users[i].firstName);
        }
    };
        /**
    this function will not work
    **/
    self.saveUser = function (user) {
        self.users.push(user);
        self.fetchAllUsers();
        $log.log("saving user");
        $uibModalStack.dismissAll();
    };

    /**
    this function works fine
    **/
    self.addNewRow = function () {
        var specialUser = {
                id : 12,
                firstName : 'john',
                lastName: 'travolta',
                homeAddress : {location:'chicago'},
                email : '[email protected]'
        };
        self.users.push(specialUser);
        $log.log("saving specialUser");
    };
    self.openCreateUser = function () {

        var modalInstance = $uibModal.open({
                animation : true,
                templateUrl : 'createUserContent',
                controller : 'UserController',
                resolve : {
                    items : function () {
                        return $scope.items;
                    }
                }
            });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    self.fetchAllUsers();
});

createUserContent.jsp

<form role="form" ng-controller="UserController as ctrl" >
    <div class="form-group">
        <label for="FirstName">FirstName</label> <input type="FirstName"
            ng-model="ctrl.user.firstName" class="form-control"
            id="FirstName" placeholder="Enter FirstName" /> <label
            for="lastName">lastName</label> <input type="lastName"
            class="form-control" id="lastName"
            ng-model="ctrl.user.lastName" placeholder="Enter lastName" />
        <label for="email">Email address</label> <input type="email"
            ng-model="ctrl.user.email" class="form-control" id="email"
            placeholder="Enter email" />
    </div>
    <div class="form-group">
        <label for="homeAddressLocation">Home Address</label> <input class="form-control"
            ng-model="ctrl.user.homeAddress.location" id="homeAddressLocation"
            placeholder="homeAddressLocation" />
    </div>
    <div class="form-group">
        <label for="SSOId">SSOId</label> <input class="form-control"
            ng-model="ctrl.user.ssoId" id="SSOId" placeholder="SSOId" />
    </div>
    <button type="submit" class="btn btn-default"
        ng-click="ctrl.saveUser(ctrl.user)">Save</button>
    <button type="submit" class="btn btn-default">Cancel</button>
</form>
Share Improve this question edited Apr 3, 2016 at 12:14 Sami Triki 4083 silver badges7 bronze badges asked Mar 31, 2016 at 9:59 BenMansourNizarBenMansourNizar 1,6284 gold badges24 silver badges45 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15 +100

Because of your modal template can't access your UserController object and doesn't show error because you used in modal template same controller so reloaded as new Ctrl doesn't refer parent Ctrl.

However better to use different controller and pass parent controller object to modal controller and then modal body can use all parent object. so you should pass parent object to modal controller.

When you include createUserContent.jsp popup file in your main file then no need to use ng-controller="UserController as ctrl" in your modal template you used in modalInstance controller : 'Ctrl',

like:

var modalInstance = $uibModal.open({
      templateUrl: 'createUserContent.jsp',
      controller: 'ModalCtrl', // ModalCtrl for modal
      controllerAs:'modal', // as modal so no need to use in modal template
      size: 'lg',
      resolve: {
        items: function () {
          return $scope.items;
        },
        parent: function(){ // pass self object as a parent to 'ModalCtrl'
                return self;
        }
      }

and ModalCtrl like:

.controller('ModalCtrl', ['parent', function (parent) {
    this.parent = parent;
}]);

here used ModalCtrl for modal as modal so you can access parent object like: modal.parent.user

template like:

<form role="form" >
    <div class="form-group">
    <label for="FirstName">FirstName</label> <input type="FirstName"
ng-model="modal.parent.user.firstName" class="form-control"
id="FirstName" placeholder="Enter FirstName" />
        .....
        ....
    <button type="submit" class="btn btn-default"
ng-click="modal.parent.saveUser(modal.parent.user)">Save</button>
    <button type="submit" class="btn btn-default">Cancel</button>
    </form>

More details Visit PLUNKER DEMO

发布评论

评论列表(0)

  1. 暂无评论