如何使用AngularJS Material对话框将数据传递给模板

时间:2018-05-16 07:14:39

标签: javascript angularjs angularjs-material

我正在使用AngularJS Material创建一个简单的评论应用程序,我希望编辑评论对话框与评论正文和用户电子邮件一起显示为双向数据绑定,但因为我正在使用带有{{1的对话框我无法弄清楚如何将评论数据传递到该URL以供我编辑。

templateUrl
    function DialogController($scope, $mdDialog) {
      
      $scope.hide = function() {
        $mdDialog.hide();
      };
    }

    $scope.editComment = function(comment) {
      $mdDialog.show({
        controller: DialogController,
        templateUrl: 'dialog.html',
        parent: angular.element(document.body),
        targetEvent: event,
        clickOutsideToClose:true,
        fullscreen: $scope.customFullscreen,
        locals: {
          comments: $scope.comments
        }
      });
      $scope.comment = comment;
      console.log(comment);
    };

1 个答案:

答案 0 :(得分:0)

我认为这是你想要实现的目标。

所以,让我们一步一步走。

  • 您应该将评论对象传递给控制器​​
  • 然后将此参数指定给对话框的范围,如果您不希望它是双向绑定,则使用angular.copy或Object.assign。
  • 在关闭函数之后,您应该将此注释对象作为参数传递,然后将其分配给您的父范围注释对象,以便它在那里更改。



    function DialogController($scope, $mdDialog, comments) {
      $scope.comment = Object.assign(comments);

      $scope.hide = function() {
        $mdDialog.hide();
      };
      
      $scope.editComment = function () {
        $mdDialog.hide($scope.comment);
      }
    }

    $scope.editComment = function(comment) {
      $mdDialog.show({
        controller: DialogController,
        templateUrl: 'dialog.html',
        parent: angular.element(document.body),
        targetEvent: event,
        clickOutsideToClose:true,
        fullscreen: $scope.customFullscreen,
        locals: {
          comments: comment
        }
      }).then(function (result) {
        comment = result;
      });
      console.log(comment);
    };

    <!-- Comments cards -->
    <div class="container">
      <div ng-repeat="($index,comment) in comments" style="margin-top:50px;">
        <div class="md-title">Comment: {{ $index + 1 }}</div>
        <br>
        <md-card>
          <md-content layout="row">
            <div class="flex-90">
              <md-card-content class="md-title">
                  {{comment.body}}
              </md-card-content>
              <md-chips>
                <md-chip> {{comment.email}} </md-chip>
              </md-chips>
            </div>
            <div class="flex" layout="row" layout-align="end start">
              <md-button class="md-icon-button"
                         ng-click="editComment(comment)">
                         <md-icon>edit</md-icon>
              </md-button>
              <md-button class="md-icon-button"
                         ng-click="deleteComment($event, comment)">
                         <md-icon>clear</md-icon>
              </md-button>
            </div>
          </md-content>
        </md-card>
      </div>
    </div>
&#13;
&#13;
&#13;