根据点击的按钮动态添加模态信息

时间:2015-03-02 23:44:25

标签: angularjs angular-ui-router angular-ui bootstrap-modal

我正在使用带有Bootstrap的AngularUI Modal和AngularUI路由器。我想填充模态标题,并根据用户单击以启动模式的按钮将项添加到提交的数组中。我可以静态添加此信息,但无法确定如何动态添加此信息。

[编辑:为以下模式添加了代码]

Javascript for Controller:

myApp.controller('NewProjectCtrl', function ($scope, $location,  $stateParams, Projects, $modalInstance) {
 var editProject = this;
 editProject.title = 'Modal 1'; // This title should change based on which button is clicked
 editProject.save = function () {
 editProject.project.type = {type: 'Basic'}; //This item should change based on which button is clicked.

 $modalInstance.close(editProject.selected);

 Projects.$add(editProject.project).then(function(data) {editProject.projects.$save({ type: 'Basic' }); //'Basic' should change based on which button is clicked.   
   });
 };
 editProject.cancel = function () {
 $modalInstance.dismiss('cancel');
   };
 });

模态的Javascript:

.state('selection.new', {
  url: '/new',
  onEnter: ['$stateParams', '$state', '$modal', function ($stateParams, $state, $modal) {
            $modal.open({
   templateUrl: 'views/new-mark.html',
   controller: 'NewProjectCtrl as editProject',
})
    .result.finally(function () {
     $state.go('^');
    });
  }]
 })

HTML:

 <!-- HTML for button that triggers modal 1 -->

 <a ui-sref="selection.new">
   <button type="button" class="btn btn-primary btn-lg" ng-click="open()">Select</button>
 </a>

 <!-- HTML for modal title -->

 <div class="modal-header">
   <h3 class="modal-title">{{editProjects.type}}</h3>
 </div>

1 个答案:

答案 0 :(得分:0)

您可以定义传递到模态实例的选项,如下所示:

JS打开模态:

$modal.open({
  templateUrl: 'views/new-mark.html',
  controller: 'NewProjectCtrl as editProject',
  resolve: {
    dialogOptions: function() {
      return {
        title: $stateParams.type === 'Basic' ? 'Basic Title' : 'Advanced Title',
        type: $stateParams.type
      };
    }
  }
})

然后在模态实例控制器中注入并使用dialogOptions:

myApp.controller('NewProjectCtrl', function ($scope, $location,  $stateParams, Projects, $modalInstance, dialogOptions) {
 var editProject = this;
 editProject.title = dialogOptions.title;
 editProject.save = function () {
 editProject.project.type = dialogOptions.type;

棘手的部分是您正在使用onEnter为您的州打开对话框。 ng-click =“open()”没有做对吗?因此,可能添加一个状态参数来表示类型 - 您可以按如下方式指定ui-sref(还需要更新状态定义):

<a ui-sref="selection.new({type: 'Basic'})">
<a ui-sref="selection.new({type: 'Advanced'})">

如果在类型中将类型设置为参数,则状态定义更改:

url: '/new?type',