gpt4 book ai didi

angularjs - $scope 不适用于 ng-template

转载 作者:行者123 更新时间:2023-12-01 11:36:29 26 4
gpt4 key购买 nike

我正在尝试使用模态来编辑表单,模态在 ng-template 脚本中,但单击编辑按钮时不显示表单数据。
$scope 不适用于模板脚本。
我创建了一个 Plunker here

$scope.setCurrentItem = function (item) {
$scope.currentItem = item;
};

$scope.edit = function (item) { //editing item
$scope.setCurrentItem(angular.copy(item));
//$scope.editItem = item;
openEditModal();
};

<!--html-->
<script type="text/ng-template" id="myModalContent.html">
<label for="name">Role: </label>
<input type="text" ng-model="currentItem.roleName" required />
</script>

我该如何解决?

最佳答案

默认情况下,ui bootstrap $modal 使用 $rootScope 作为其默认范围。但是您假设它会自动占用打开对话框的 Controller 的范围,但这并没有发生。但是有一个 scope 属性,您可以设置该属性以将范围传递给 ui modal,以便它使用该范围并在提供的范围之外创建一个子范围,并将用作基础范围对于模态。因此,让您的模态包装器在其设置中也采用 scope 属性并将其传递。

From Doc

scope - a scope instance to be used for the modal's content (actually the $modal service is going to create a child scope of a provided scope). Defaults to $rootScope.

示例更改:-

  function openEditModal() {
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Save role',
headerText: 'Edit role',
bodyText: '',
scope:$scope //<-- Pass scope
};

Modal.showModal({ templateUrl: 'myModalContent.html', size: 'lg' }, modalOptions).then(function (result) {
console.log("save!", result);
});
}

在您的服务中:-

  /*I just did this here based on my limited understanding of your code*/
return $modal.open(angular.extend(tempModalDefaults, customModalOptions)).result;

从您的模态模板传回项目,我不确定您的模板是否通用,如果是,那么您可能需要采用不同的方法来传回数据:-

  <button class="btn btn-primary" ng-click="modalOptions.ok(currentItem)">{{modalOptions.actionButtonText}}</button>

Demo

关于angularjs - $scope 不适用于 ng-template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26622144/

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