2015-04-22 58 views
0

當我第二次觸發被刪除。任何想法?如果您需要查看更多我的代碼,請告訴我。AngularJS - 共享服務對象被錯誤刪除

controller.js

crtPromoCtrl.controller('surveyCtrl', ['$scope', 'surveySrv', function($scope, surveySrv) 
{ 
    $scope.questions = surveySrv.getQuestions(); 

    $scope.editQuestion = function(index) 
    { 
     surveySrv.setEditQuestion(index); 
    }; 

    $scope.deleteQuestion = function(index) 
    { 
     $(document).off('click', '#confirmationModal #confirm'); 
     $('#confirmationModal').modal('show'); 

     $(document).on('click', '#confirmationModal #confirm', function() 
     { 
      surveySrv.deleteQuestion(index); 

      $scope.$apply(); 
     }); 
    }; 
}]); 

service.js

crtPromoSrv.service('surveySrv', function() 
{ 
    var questions = []; 
    var editQuestion; 

    this.getQuestions = function() 
    { 
     return questions; 
    }; 

    this.addQuestion = function(question) 
    { 
     questions.push(question); 
    }; 

    this.setEditQuestion = function(index) 
    { 
     editQuestion = questions[index]; 
    }; 

    this.getEditQuestion = function() 
    { 
     return editQuestion; 
    }; 

    this.clearEditQuestion = function() 
    { 
     editQuestion = undefined; 
    }; 

    this.deleteQuestion = function(index) 
    { 
     questions.splice(index, 1); 
     console.log(questions); 
    }; 
}); 

編輯:我想這是一個事件傳播的事情,因爲當我有5個Q的它刪除#2和#3當我刪除#2。

編輯:修正,請參閱controller.js代碼。

+0

永遠(永遠)不在控制器中進行DOM操作。這是規則#1在嘗試構建模塊化代碼時試圖使用Angular進行測試。控制器應該從後備陣列中移除項目。操縱DOM是指令的意圖。 – Enzey

+0

明白了,謝謝! – jstudios

回答

1

看起來您多次將'click'函數添加到您的按鈕。第一次調用$scope.deleteQuestion時,它添加了該功能。第二次調用它時,它會再次加上,所以當它被點擊時,函數被調用兩次。

一個簡單的解決方法是解除'click'事件之前再次添加它。像這樣:$('#confirmationModal #confirm').off('click');

更好解決方案這裏是不使用jQuery的這些事件綁定。使用一個簡單的Angular模態指令(例如Angular-UI庫中提供的指令)將是正確的方法。然後你可以在按鈕上只有一個ng-click,永遠不會有這個問題。

+0

嘗試此操作,並在沒有運氣的情況下解除其他答案。如果它很重要,它似乎最多隻能觸發2次,換句話說,第三次點擊它時不會觸發它3次,等等。 – jstudios

+1

我會建議改變它做Angular方式,就像我提到的那樣。你可以使用Angular-UI Modal指令[這裏](https://angular-ui.github.io/bootstrap/)。或者如果你想要一些已經完成的「確認」,你可以使用[this]這樣的東西(http://schlogen.github.io/angular-confirm/) – brettvd

+0

我通過把'off'放在'而不是反過來。這將是一個短暫的解決方案,因爲我打算儘快採用「角度」方式。謝謝! – jstudios