javascript - 模式窗口中的范围(AngularJS 指令)

标签 javascript twitter-bootstrap angularjs

我正在尝试使用模态窗口(参见 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);
}

http://plnkr.co/edit/Ty10C8JOKHlwb2bWA89r?p=info

关于javascript - 模式窗口中的范围(AngularJS 指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19181743/

相关文章:

javascript - 如果我只有两个 if 条件,我该如何制定指令? - Angular Js

javascript - 有效字段更改后,Formik 调度 Redux 操作

javascript - Google Analytics 跟踪 pdf 下载

javascript - 具有间隔函数的 async.eachSeries

php - 使用 Splice() 获取正确的索引

angularjs - ui-grid 不显示提供给它的完整行数

javascript - 从 Rails 中的 Controller 功能填充选择框

html - 如何在 bootstrap 表格单元格中显示重叠的图片?

导航栏顶部的 Twitter-Bootstrap-2 Logo 图像

javascript - Twitter bootstrap typeahead 自定义按键 ENTER 功能