2015-04-07 126 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); 
       });  
      } 
相关问题