我正在尝试使用模态窗口(参见 http://angular-ui.github.io/bootstrap/ )。
在父 Controller 中我有以下功能:
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
year: function () {
return $scope.year.value;
},
month: function () {
return $scope.month;
},
day: function () {
return $scope.day.name;
},
todos: function () {
return $scope.day.toDoItems;
}
},
backdrop: 'static'
});
modalInstance.result.then(function (todos) {
angular.forEach(todos, function (todo) {
if (todo.New)
$scope.day.toDoItems.push(todo);
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
在模态 Controller 中有一个 addTodo 函数:
var ModalInstanceCtrl = function ($scope, $modalInstance, year, month, day, todos) {
...
$scope.todos = todos;
$scope.addTodo = function () {
$scope.todos.push({ TodoText: $scope.todoText.value, Done: false, Del: false, Date: new Date(year, month, day), Priority: 1, New: true});
$scope.todoText.value = "";
};
...
$scope.ok = function () {
$modalInstance.close($scope.todos);
};
};
在父 View 中显示了一个日历,其中包含每天的todos
。单击一天的标题时,模式窗口会打开,您可以添加待办事项。我的问题是,在模态窗口中添加待办事项时,todos
也会同时添加到父 View 。
现在,todos
在父 View 中添加了两次:一次是在模态视图中添加,一次是我在模态视图中单击“确定”。
但我希望仅当在模态视图上单击“确定”时才将 todos
项添加到父 View 。
有人解决这个问题吗?提前致谢!
您可以在 Plunker 中看到它是如何工作的:http://plnkr.co/edit/Nr1h7K3WZyWlRlrwzhM3?p=info
最佳答案
在模态 Controller 的解析对象中,您实际上是将父级的范围 todos 对象作为引用传回,因此当您在模态 Controller $scope.todos = todos;
中分配它时,它实际上指向父级的 todos
范围变量。您可以返回父级待办事项的副本,而不是对变量的引用。
todos: function () {
return angular.copy($scope.day.toDoItems);
}
关于javascript - 模式窗口中的范围(AngularJS 指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19181743/