2015-04-07 63 views
0

在下面的示例待辦事項列表中,您可以通過按藍色添加按鈕來添加項目,並使用刪除按鈕刪除帶勾號的項目。在控制器之間切換,無法更新視圖

但是,一旦刪除了任何項目,添加項目不會更新視圖。我懷疑我的麻煩在於讓兩個控制器訪問todos變量。

DEMO

(function(){ 
'use strict'; 

angular.module('todoApp', ['ngMaterial', 'ngAnimate', 'ngAria' ]) 

    .directive('mainApp', function(){ 
     return { 
      restrict: 'E', 
      templateUrl: 'app.html', 
      controller: function($scope, $mdDialog){ 
       $scope.todos = todos; 

       $scope.someCompleted = function(){ 
        for (var i = 0; i < $scope.todos.length; i++) { 
         if ($scope.todos[i].done === true) { 
          return true; 
         } 
        } 
       }; 
       $scope.clearCompleted = function(){ 
        $scope.todos = $scope.todos.filter(function(item){ 
         return !item.done; 
        }); 
       }; 
       $scope.showAdvanced = function(ev) { 
        $mdDialog.show({ 
         controller: DialogController, 
         templateUrl: 'addDialog.html', 
         targetEvent: ev, 
        }); 
       }; 

      }, 
      controlerAs: 'list' 
     }; 

    }) 

; 
function DialogController($scope, $mdDialog) { 
    $scope.todos = todos; 
    $scope.hide = function() { 
     $mdDialog.hide(); 
    }; 
    $scope.cancel = function() { 
     $mdDialog.cancel(); 
    }; 
    $scope.answer = function(answer) { 
     $mdDialog.hide(answer); 
    }; 
    $scope.addTodo = function(){ 
     $scope.todos.push({name: $scope.newTodo, done: false}); 
     $scope.newTodo = null; 
     $mdDialog.hide(); 
    }; 
} 

var todos = []; 



})(); 

回答

1

在開始的時候,無論是在主控制器和DialogController指向「待辦事項」數組$ scope.todos,所以當你添加新項目可顯示。

在clearComplete函數中,$ scope.todos現在指向另一個數組,而Dialog控制器中的$ scope.todos仍然指向「todo」數組,因此當「todo」數組更新時,$主控制器中的scope.todos保持不變。

更改clearComplete的代碼到這個:

$scope.clearCompleted = function(){ 
    todos = todos.filter(function(item){return !item.done;}); 
    $scope.todos = todo; //It might run without this line, just to make sure 
}; 

順便說一句,對於這個高貴的解決方案應該是:使用$ rootscope和廣播。更改DialogController的代碼:

function DialogController($scope, $mdDialog, $rootScope) { 
    //$scope.todos = todos; //Remove this line 

    $scope.addTodo = function(){ 
     //Broadcast an event, main controller will catch this 
     $rootScope.$broadcast("NoteAdded", {name: $scope.newTodo, done: false}); 
     $scope.newTodo = null; 
     $mdDialog.hide(); 
    }; 
} 

然後在主控制器捕捉事件:

controller: function($scope, $mdDialog){ 
       $scope.todos = todos; 

       //other codes 

       $scope.$on("NoteAdded", function(event, item){ 
         $scope.todos.push(item); 
       });  
      } 
相關問題