Angular UI Bootstrap模态框更新$scope。

32 浏览
0 Comments

Angular UI Bootstrap模态框更新$scope。

我想使用模态框来编辑我的数据。我将数据传递给模态框实例。当我点击确定时,我将编辑后的数据传递回控制器的$scope.selected。然后,我想更新原始的$scope。但是不知怎的,$scope没有更新。我做错了什么?\n变量ModalDemoCtrl = function ($scope, $modal, $log) {\n $scope.data = { name: \'\', serial: \'\' }\n $scope.edit = function (theIndex) {\n var modalInstance = $modal.open({\n templateUrl: \'myModalContent.html\',\n controller: ModalInstanceCtrl,\n resolve: {\n items: function () {\n return $scope.data[theIndex];\n }\n }\n });\n modalInstance.result.then(function (selectedItem) {\n $scope.selected = selectedItem;\n // 这里是数据更新的地方,但是并没有实现\n $scope.data.name = $scope.selected.name;\n $scope.data.serial = $scope.selected.serial;\n });\n };\n};\n模态框控制器:\n变量ModalInstanceCtrl = function ($scope, $modalInstance, items) {\n $scope.items = items;\n $scope.selected = {\n name: $scope.items.name,\n serial: $scope.items.serial\n };\n $scope.ok = function () {\n $modalInstance.close($scope.selected);\n };\n $scope.cancel = function () {\n $modalInstance.dismiss(\'cancel\');\n };\n};\n模态框:\n

{{ name }}

\n\n\n\n

0
0 Comments

问题的原因是在模板中使用了ng-repeat,但是在点击事件中没有正确地更新$scope中的属性。解决方法是使用对象来作为模型,并在对象上设置属性,而不是直接赋予新的值。

在这个问题中,通过观察代码片段:

$scope.ok = function () {
    $modalInstance.close($scope.selected);
};

可以发现,在模板中可能是这样使用ng-repeat的:

<li ng-repeat="item in items">
    <a ng-click="selected = item">{{ item }}</a>
</li>

,而不是这样的:

<li ng-repeat="item in items">
    <a ng-click="selected.item = item">{{ item }}</a>
</li>

如果是这样的情况,那么在这个例子中,你是在子作用域中分配了selected,这不会影响父作用域中的selected属性。因此,当你尝试访问$scope.selected.name时,它将是空的。

一般来说,应该使用对象作为模型,并在对象上设置属性,而不是直接赋予新的值。

此外,你还没有将输入与任何模型进行绑定,因此你在那里输入的数据不会被存储在任何地方。你需要使用ng-model来实现绑定,例如:

<input type="text" ng-model="editable.serial" />
<input type="text" ng-model="editable.name" />

你可以参考这个plunkr中的示例来解决问题。

0