简体   繁体   中英

The function runs only once when updating parent controller scope in opened Angular UI Bootstrap Modal

I have a problem after refactoring code of Test Application backend. Test has questions and answers, each question has multiple answers and only one of them is correct.

After some debugging everything seems to work fine, but all questions and answers managing logic was located in one controller. I moved answers logic to separate nested controller and after that stuck with this problem. Tried different methods but none of them helped.

The goal is to combine Angular UI Tree (Example #4 - Groups & Categories) with Angular UI Bootstrap Modal.

By design adding and editing questions and answers are happening in modal window. The template is located separately so it's not repeated with each question and answer. When provided data is not valid, validation errors are shown, otherwise the success alert is shown and all fields clear and back to default state (all that happens inside the modal window, it's stay opened and can be closed only by hitting "Cancel", X button or keyboard Esc button).

I need to update QuestionsCtrl $scope.questions from modal window (trigger button is located inside template of modal window). After hitting "Add" button $scope.questions will become updated in scope and the ui.tree is also updated in background. The success alert or validation errors doesn't shown, form fields doesn't clear. Repeated clicks is not calling the actual function again (so it runs only once).

Without modal window but with nested controllers adding works fine.

I created plunk and removed all redundant code so focusing on the problem will be easier. I can provide more code if it's needed. For example in the plunk results of console.log shown only once.

It's not that it's not working. But you're setting data wrong. When you write:

$scope.add = function() {
    console.log('!!!');
    var data = [{"dataType":"question","id":2,"name":"1. Question 1","answers":[{"dataType":"answer","id":7,"name":"1. Answer 1","correct":false},{"dataType":"answer","id":8,"name":"2. Answer 2","correct":false},{"dataType":"answer","id":9,"name":"3. Answer 3","correct":false}]}];;
    $scope.setQuestions(data);
  };

and:

 $scope.setQuestions = function(data) {
    $scope.questions = data;
  };

you're forcing the questions collection to be data instead of adding new items. So it's like initializing the questions array all over again. For this to work you need to use this kind setQuestions function:

$scope.setQuestions = function(data) {
    $scope.questions.push(data);
  };

that way your new question will be added to the already existing ones.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM