gpt4 book ai didi

angularjs - Angular UI Bootstrap 模态更新 $scope

转载 作者:行者123 更新时间:2023-12-03 06:22:43 24 4
gpt4 key购买 nike

我想使用模式来编辑我的数据。我将数据传递给模式实例。当我单击“确定”时,我将 $scope.selected 中编辑的数据传递回 Controller 。

我想更新原来的$scope。但不知何故 $scope 没有更新。我做错了什么?

var ModalDemoCtrl = function ($scope, $modal, $log) {

$scope.data = { name: '', serial: '' }

$scope.edit = function (theIndex) {

var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
items: function () {
return $scope.data[theIndex];
}
}
});

modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;

// this is where the data gets updated, but doesn't do it
$scope.data.name = $scope.selected.name;
$scope.data.serial = $scope.selected.serial;

});
};
};

模态 Controller :

var ModalInstanceCtrl = function ($scope, $modalInstance, items) {

$scope.items = items;
$scope.selected = {
name: $scope.items.name,
serial: $scope.items.serial
};

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

$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};

模态:

<div class="modal-header">
<h3>{{ name }}</h3>
</div>
<div class="modal-body">
<input type="text" value="{{ serial }}">
<input type="text" value="{{ name }}">
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

最佳答案

您没有包含模态模板,所以这有点猜测。您的代码与 angular-ui 模式的示例代码非常接近,它在模板中使用 ng-repeat 。如果您正在做同样的事情,那么您应该知道 ng-repeat 创建了一个从父级继承的子级作用域。

从这个片段来看:

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

看起来不像在模板中这样做:

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

你可能会做这样的事情:

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

如果是这样,那么在您的情况下,您将在子作用域中分配 selected ,这不会影响父作用域的 selected 属性。然后,当您尝试访问 $scope.selected.name 时,它将为空。一般来说,您应该为模型使用对象,并为其设置属性,而不是直接分配新值。

This part of the documentation更详细地解释了范围问题。

编辑:

您也根本没有将输入绑定(bind)到任何模型,因此您输入的数据永远不会存储在任何地方。您需要使用 ng-model 来做到这一点,例如:

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

参见this plunkr一个工作示例。

关于angularjs - Angular UI Bootstrap 模态更新 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20592803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com