如何在模态中设置自定义单选按钮的默认值

问题描述 投票:0回答:1

背景:

因此,我正在使用模式框来搜索数据库中的任务条目列表,使用表单来缩小结果。在此模式框中,有一个自定义单选按钮,用于选择任务是否正在进行(简单的“是”或“否”选项)。目标是在调用模态时将“否”选项设置为默认值。目前,我正在使用data-ng-init;但是,这仅在第一次打开模态时起作用。如果用户关闭模态并重新打开它,则不再设置默认值。以下是此自定义按钮的示例:

<div class="col-sm-6">
      <div style="margin-bottom:10px">
      <button type="button" data-ng-init="tr.taskInProgress('No')" 
          title="Task In Progress: No" data-ng-click="tr.taskInProgress('No')"
          style="border:0;background:transparent">
      <img src="../images/selected.png" data-ng-switch-when="No" />
      <img src="../images/Deselect.png" data-ng-switch-when="Yes"  />
      <img data-ng-switch-when="" src="/nc/images/Deselect.png" /></button>
          <text>No
   </div>
   (another similar button, but for 'yes')
</div>

在随附的.js文件中,以下内容用于帮助填充此模式:

/*--------- Get Tasks ---------*/
tr.closeGetTaskModal = closeGetTasModal;
tr.displayGetTaskMessage = true;
tr.selectedStatusType = getStatusType;
tr.trackingId = '';
tr.performGetTask = performGetTask;
tr.isTaskInProgess = isTaskInProgress;

并且,在相同的.js文件中,以下函数用于修改无线电:

function isTaskInProgress(newValue) {
    tr.isTaskInProgress = newValue;
}

我一直在寻找他们如何处理这些案件的其他迭代,但我一直不幸,并没有发现任何类似于我正在使用的工作。我已经尝试通过修改Get TasksisTaskInProgress('No')部分设置默认值,但这只锁定了模态,我无法修改该选项。我试过在isTaskInProgress函数中设置默认值;但是,这仅在单击按钮时有效,无法设置默认值。我试着看看data-ng-default是否会起作用;然而,这似乎不是一个公认的参数。有没有人有关于如何修改它以获得所需结果的建议?提前感谢大家的帮助

angularjs modal-dialog default-value
1个回答
1
投票

小免责声明

我冒昧地假设你正在使用UI Bootstrap(因为我在你的示例HTML中看到了bootstrap类),所以在我的例子中将使用Uib Modal。

Bootstrap Modal docs:https://angular-ui.github.io/bootstrap/#!#modal


解析器/回调解决方案

您很可能希望使用控制器来设置tr.isTaskInProgress标志,而不是使用ng-init指令(更灵活/可读性更强)。

在目标控制器函数的顶部将tr.isTaskInProgress设置为false,然后将其值作为“模态解析对象”中的属性传递给模态。

Bootstrap对Resolve对象的解释:https://angular-ui.github.io/bootstrap/#!#ui-router-resolves


function MainController($scope, $uibModal) {
    let vm = this;
    vm.isTaskInProgress = false;

    // When you open the modal, pass in the isTaskProgress value
    let modalInstance = $uibModal.open({
         templateUrl: 'myModalContent.html', // Points to the script template
         controller: 'ModalController', // Points to the controller
         controllerAs: 'mc',
         windowClass: 'app-modal-window',
         backdrop: 'static',
         resolve: {
              isTaskInProgress: function() {
                   // pass the task state to the Modal
                   return vm.isTaskInProgress;
              }
         }
     });

  // handle the value(s) passed back from the modal
  modalInstance.result.then(returnedTaskState => {
    // reassign the returned value of the modal
    if (returnedTaskState !== null) {
      vm.isTaskInProgress = returnedTaskState;
    }
  });
}

工作实例

https://plnkr.co/ryK7rG

为了节省时间,我已经改变了一些变量/方法名称与你在片段中的名称。在示例中,您可以...

  • 在打开模态之前设置“正在进行”值,模态反映“正在进行”值。
  • 更改模态内的“正在进行”值。关闭模态时,将在主页面中更新该值。

SO片段

我意识到SO Snippet窗口并不是这个例子的最佳位置,但只是在这里抛出我的示例代码,以防Plunker因某些原因而不方便。

(function() {
  "use strict";

  let app = angular
    .module("myApp", ["ui.bootstrap"])
    .controller("MainController", MainController);

  MainController.$inject = ["$scope", "$timeout", "$uibModal"];

  function MainController($scope, $timeout, $uibModal) {
    /**
     * John Papa Style Guide
     * https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
     * */
    let vm = this;

    // ==== scoped variables ====
    vm.title = "AngularJS - Passing Toggled Values to a Modal"
    vm.taskInProgress = false;
    vm.taskButtonLocked = false;

    // ==== functions hoist ====
    vm.beginTask = _beginTask;

    function _beginTask() {
      vm.modalIsOpen = true;

      // do work

      openModal();
    }

    // ==== local functions ====
    function openModal() {
      // open the modal with configurations
      let modalInstance = $uibModal.open({
        templateUrl: 'myModalContent.html', // Points to my script template
        controller: 'ModalController', // Points to my controller
        controllerAs: 'mc',
        windowClass: 'app-modal-window',
        backdrop: 'static',
        resolve: {
          taskInProgress: function() {
            // pass the task state to the Modal
            return vm.taskInProgress;
          }
        }
      });

      // handle the value(s) passed back from the modal
      modalInstance.result.then(returnedTaskState => {
        // reset control values after modal is closed
        vm.taskButtonLocked = false;
        vm.modalIsOpen = false;

        // reassign the returned value of the modal
        console.log("returnedTaskState: ", returnedTaskState);

        if (returnedTaskState !== null) {
          vm.taskInProgress = returnedTaskState;
        }
      });
    }
  }

})();

(function() {
  'use strict';

  angular
    .module('myApp')
    .controller('ModalController', ModalController);

  ModalController.$inject = ['$scope', '$timeout', '$uibModalInstance', 'taskInProgress'];

  function ModalController($scope, $timeout, $uibModalInstance, taskInProgress) {

    // Assign Cats to a Modal Controller variable
    let vm = this;
    
    vm.inProgress = taskInProgress;
    
    console.log("taskInProgress", taskInProgress)

    $scope.submit = function() {
      $uibModalInstance.close(vm.inProgress);
    }

    $scope.close = function() {
      $uibModalInstance.close(null);
    }
  }
})();
input[type="radio"]:hover {
  cursor: pointer;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunk</title>

  <link rel="stylesheet" href="style.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <!-- JQuery and Bootstrap -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <!-- Angular Stuff -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.js"></script>
  
   <!-- UI Bootstrap Stuff -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>

  <!-- Our Angularjs App -->
  <script type="text/javascript" src="app.js"></script>
</head>

<body ng-app="myApp" ng-controller="MainController as tr">

  <!-- ==== MAIN APP HTML ==== -->
  <div class="container" style="padding:1em;">
    <div class="row">
      <div class="col-xs-12">
        <div class="jumbotron text-center">
          <h2>{{ tr.title }}</h2>
          <h4><em><a href="https://stackoverflow.com/questions/55362380/how-to-set-default-value-of-custom-radio-button-in-a-modal" target="_blank">SO Question #55362380</a></em></h4>
          <h4><em><a href="https://angularjs.org/" target="_blank">AngularJS - v1.7.8</a></em></h4>
        </div>
      </div>
      <div class="col-xs-12">
        <form>
          <div class="form-group">
            <h3>Task In Progress</h3>
            <div>
              <label>Yes:</label>
              <input type="radio"
                     ng-checked="tr.taskInProgress"
                     ng-click="tr.taskInProgress = true"
                     ng-disabled="tr.modalIsOpen">
            </div>
            <label>No:</label>
            <input type="radio" 
                   ng-checked="!tr.taskInProgress"
                   ng-click="tr.taskInProgress = false" 
                   ng-disabled="tr.modalIsOpen">
          </div>
          <div class="form-group">
            <label>Open the modal:</label>
            <button type="button" 
                    class="btn btn-success" 
                    ng-click="tr.beginTask();" 
                    ng-disabled="tr.taskButtonLocked">
              <span>Begin Task</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
  
  <!-- ==== MODAL HTML TEMPLATE ==== -->
   <script type="text/ng-template" id="myModalContent.html">
    <div class="modal-header">
      <h3 class="modal-title" id="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body" id="modal-body">
        <form>
          <div class="form-group">
            <label>Task State:</label>
            <div style="padding:1em;background:rgba(200, 214, 229,0.3);">
              <p>
                <span ng-show="!mc.inProgress">
                  <span>Task is not in progress...&nbsp;&nbsp;</span>
                  <i class="fa fa-check-square" aria-hidden="true"></i>
                </span>
                <span ng-show="mc.inProgress">
                  <span>Task is in progress...&nbsp;&nbsp;</span>
                  <i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
                </span>
              </p>
            </div>
          </div>
          <div class="form-group" style="padding-top:1em;">
            <h3>Task In Progress</h3>
            <div>
              <label>Yes:</label>
              <input type="radio"
                     ng-checked="mc.inProgress"
                     ng-click="mc.inProgress = true">
            </div>
            <label>No:</label>
            <input type="radio" 
                   ng-checked="!mc.inProgress"
                   ng-click="mc.inProgress = false">
          </div>
        </form>
      </div>
    <div class="modal-footer">
      <button class="btn btn-primary" type="button" ng-click="submit()">OK</button>
      <button class="btn btn-warning" type="button" ng-click="close()">Cancel</button>
    </div>
  </script>

</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.