Angular Js Controller函数被调用两次

时间:2017-09-01 08:10:35

标签: javascript angularjs components

我在几个组件上面临这个问题。这是其中之一:

控制器:

function eventsListController($scope, $rootScope, $state, $localStorage, $mdDialog, communityApi, $stateParams, $cookies) {
    const self = this;
    console.log($scope);
    console.log(self);
    console.log(this);
    let currentUserId = $cookies.getObject('userId');
    self.communityEvents = [];
    let joinCalled = false;
    self.todayDate = moment();
    self.eventDialog = function () {
        $mdDialog.show({
            scope: $scope,
            preserveScope: true,
            templateUrl: './src/app/components/events/dialogs/createEvents.html',
            clickOutsideToClose: false
        });
    };

    self.joinEvent = function (event, index) {
        if (!joinCalled) {
            joinCalled = true;
            communityApi('joinCancelCommunityEvents', {}, {
                'eventId': event._id,
                action: 'join'
            }).then((res) => {
                $mdDialog.show(
                    $mdDialog.alert()
                    .clickOutsideToClose(true)
                    .textContent('You successfully joined event.')
                    .ok('Got it!')
                );
                self.communityEvents[index].attendees.push(currentUserId);
                joinCalled = false;
            }, (error) => {
                joinCalled = false;
            })

            // $mdDialog.show({
            //     scope: $scope,
            //     preserveScope: true,
            //     templateUrl: './src/app/components/events/dialogs/joinEvents.html',
            //     clickOutsideToClose: false
            // });
        }
    };

    self.cancelEvent = function (event) {
        communityApi('joinCancelCommunityEvents', {}, {
            'eventId': event._id,
            action: 'cancel'
        }).then((res) => {
            $mdDialog.show(
                $mdDialog.alert()
                .clickOutsideToClose(true)
                .textContent('You successfully cancel event join.')
                .ok('Got it!')
            );
            getCommunityEvents();
        }, (error) => {})
    };


    self.createEvent = function () {
        self.eventData.date = moment(self.eventData.selectedDate._d).toISOString();
        console.log(self.eventData);
        var address = self.eventData.address.getPlace() ? self.eventData.address.getPlace() : self.eventData.address;
        if (address.formatted_address) {
            self.eventData.address = address.name ? address.name + ', ' + address.formatted_address : address.formatted_address;
            self.eventData.lat = address.geometry.location.lat();
            self.eventData.long = address.geometry.location.lng();
        }
        communityApi('postCommunityEvents', self.eventData).then((res) => {
            self.cancelDialog();
        }, (error) => {
            console.log(error, 'getCommunityEvents')
        })
    };

    self.cancelDialog = function () {
        $mdDialog.cancel();
    };

    self.checkJoin = function (data) {
        return (data.indexOf(currentUserId) === -1) ? false : true;
    };

    function getCommunityEvents() {
        communityApi('getCommunityEvents').then((res) => {
            self.communityEvents = res;
        }, (error) => {
            console.log(error, 'getCommunityEvents')
        })
    };
    getCommunityEvents();
};

我的apis服务是:

'use strict';

export const apiModule = angular.module('app.api', [])
    .config(['$httpProvider', function ($httpProvider) {

        //Support for resolving multiple async calls within one digest cycle.
        $httpProvider.useApplyAsync(true);
    }])
    .provider("communityApi", [function () {
        this.$get = ['$rootScope', '$state', '$window', '$http', '$q', 'apiEndpoints', '$cookies', '$mdDialog', function ($rootScope, $state, $window, $http, $q, apiEndpoints, $cookies, $mdDialog) {
            function apiService(endpointName, _config_, restfullParams, fullResponse) {
                var config = apiEndpoints[endpointName];

                if (config === undefined) {
                    throw new Error('API config not found in endpointConfig. Please check api.Endpoints');
                    return;
                } else {
                    config = angular.copy(config);
                    //Inject Restful params here.
                    if (restfullParams) {
                        config.url = injectRestfullParams(config.url, restfullParams);
                    }
                    config.url = $rootScope.imageUrlPre + "/api" + config.url;
                }

                function injectRestfullParams(_url_, paramObj) {
                    var url = _url_;
                    angular.forEach(paramObj, function (value, key) {
                        url = url.replace(':' + key, value);
                    });

                    return url;
                }

                // angular.extend(config, _config_);
                config.data = angular.copy(_config_);
                config.method = config.method || 'GET';

                function success(response) {
                    if (fullResponse) {
                        defer.resolve(response);
                    } else {
                        defer.resolve(response.data);
                    }
                }

                function error(response) {
                    switch (response.status) {
                        // case 401:
                        //     $cookies.remove("authCommunity");
                        //     $window.location.href = $window.location.origin + "/community/login";
                        //     break;
                        // case 502:
                        //     break;

                            // Default   
                        default:
                            defer.reject(response);
                            break;
                    }
                }

                var defer = $q.defer();
                $http(config).then(success, error);
                return defer.promise;

            }

            return apiService;
        }]
    }])
    .value('apiEndpoints', {
        'userInfo': {
            url: '/users/me',
            method: 'GET',
        },
        'login': {
            url: '/users/verify/:mobile/:otp',
            method: 'GET',
        },
        'signup': {
            url: '/users/update',
            method: 'PUT',
        },
        'getOTP': {
            url: '/users/app',
            method: 'POST',
        },
        'createJob': {
            url: '/community/job',
            method: 'POST',
        },
        'getJobs': {
            url: '/community/job',
            method: 'GET',
        },
        'getIndividualJob': {
            url: '/community/job/:jobId',
            method: 'GET',
        },
        'postComment': {
            url: '/community/comment/:jobId',
            method: 'POST',
        },
        'deletePost': {
            url: '/community/job/:jobId',
            method: 'DELETE',
        },
        'editPost': {
            url: '/community/job/:jobId',
            method: 'PUT',
        },
        'getActivities': {
            url: '/community/activity',
            method: 'GET',
        },
        'getNearbyPeople': {
            url: '/community/people?long=:long&lat=:lat',
            method: 'GET',
        },
        'getAllPeople': {
            url: '/community/people',
            method: 'GET',
        },
        'getIndividualUserInfo': {
            url: '/community/people?userId=:id',
            method: 'GET',
        },
        'getChat': {
            url: '/community/chat',
            method: 'GET'
        },
        'getSingleChat': {
            url: '/community/chat/:roomId',
            method: 'GET'
        },
        'getCommunityEvents': {
            url: '/community/event',
            method: 'GET'
        },
        'postCommunityEvents': {
            url: '/community/event',
            method: 'POST'
        },
        'joinCancelCommunityEvents': {
            url: '/community/event/:eventId/:action',
            method: 'PUT'
        },
        'submitCommunityIdData': {
            url: '/users/app/new',
            method: 'POST'
        },
        'confirmCommunityId': {
            url: '/users/:communityId',
            method: 'GET'
        },
        'varifyCommunityIdOtp': {
            url: '/users/verify/:mobile/:token',
            method: 'GET'
        },
        'getNews': {
            url: '/community/news',
            method: 'GET'
        },
        'addNews': {
            url: '/community/news',
            method: 'POST'
        },
        'checkBookingAvailablity': {
            url: '/plans/available',
            method: 'POST'
        },
        'bookVvsSeats': {
            url: '/plans/book',
            method: 'POST'
        },
        'getAllBookings': {
            url: '/users/mybookings',
            method: 'GET'
        },
        'deleteBooking': {
            url: '/plans/booking/:bookingId',
            method: 'DELETE'
        },

    })
    .name

HTML模板:

<md-button class="md-fab md-fab-bottom-right" ng-click="ctrl.eventDialog()" aria-label="addevents" style="position:fixed">
    <i class="fa fa-edit" style="font-size:30px;color:white;display:block"></i>
</md-button>

<md-card ng-repeat="event in ctrl.communityEvents track by $index" ng-if="event.description">
    <md-card-header ng-if="!event.thirdParty">
        <md-card-avatar>
            <img class="md-user-avatar" src="src/assets/images/sample.jpeg" ng-if="!event.organizer.profile_image" style="border-radius:50%;height:50px;width:50px" />
            <img class="md-user-avatar" src="{{$root.imageUrlPre}}/{{event.organizer.profile_image}}" ng-if="event.organizer.profile_image" style="border-radius:50%;height:50px;width:50px" />
        </md-card-avatar>
        <md-card-header-text style="padding:6px 0 0 10px">
            <span><a class="md-title" style="cursor:pointer" ng-click="ctrl.openProfile(event.organizer._id)">{{event.organizer.name}}</a></span>
        </md-card-header-text>
    </md-card-header>
    <md-card-title>
        <md-card-title-text>
            <span class="md-headline" ng-if="!event.link">{{event.title}}</span>
            <span class="md-headline" ng-if="event.link"><a style="font-size: large;" href="{{event.link}}" target="_blank">{{event.title}}</a></span>
            <!-- <span class="md-headline" ng-if="event.link"><a style="border-bottom: 1px solid;" href="{{event.link}}">{{event.title}}</a></span> -->
            <div style="padding-top:15px">
                <p><strong>Date -</strong> {{event.date | date}}</p>
                <p><strong>Time - </strong>{{event.date | date : 'shortTime'}}</p>
                <p><strong>Address - </strong>{{event.address}}</p>

            </div>
        </md-card-title-text>
    </md-card-title>
    <md-card-content ng-init="discriptionLength=250">
        <div>
            <p>
                {{event.description | limitTo: discriptionLength}} <span ng-show="event.description.length > 250 && discriptionLength == 250">...</span></br>
            </p>
        </div>
        <div>
            <p>
                <div ng-if="!event.link"><span>Attendees</span> - {{event.attendees.length}}</div>

                <a ng-show="event.description.length > 250 && discriptionLength == 250" style="cursor:pointer;float:right" ng-click="discriptionLength = event.description.length"><i class="fa fa-arrow-down" aria-hidden="true"></i></a>
                <a ng-show="event.description.length > 250 && discriptionLength > 250" style="cursor:pointer;float:right" ng-click="discriptionLength = 250"><i class="fa fa-arrow-up" aria-hidden="true"></i></a>
            </p>
            <button ng-if="ctrl.checkJoin(event.attendees) && !event.link" ng-click="ctrl.cancelEvent(event, $index)" class="btn btn-primary">Cancel join</button>
            <button ng-if="!ctrl.checkJoin(event.attendees) && !event.link" ng-click="ctrl.joinEvent(event, $index)" class="btn btn-primary">Join event</button>
            <a style="font-size: large;" ng-if="event.link" href="{{event.link}}" target="_blank">More...</a>
        </div>
    </md-card-content>
</md-card>
<div ng-if="ctrl.communityEvents.length == 0" style="display: flex;justify-content: center;height: 100%;align-items: center;">
    <h3>Sorry! no events to view.</h3>
</div>

所以问题是控制器函数被调用两次,并且是随机的。不是每次都会发生这种情况,而是随机发生的。

我注意到,当发生这种情况时,在调用一次函数后,self会有整个window对象。

任何人都可以帮助我,因为这种奇怪的事情正在弄乱我的整个应用程序。

0 个答案:

没有答案