使用AngularJS以详细模式加载数据

时间:2016-04-06 08:43:36

标签: javascript angularjs angularjs-directive modal-dialog

我正在尝试使用AngularJS将数据加载到模态中。我把数据加载到“卡片”列表中,它工作正常。但是,对于每张卡,我需要打开一个详细模式并加载其中的其余数据。请关注我的代码:

// index.html的一部分

<body ng-controller="CardsController">
  <div class="container">

    <div class="cards" ng-repeat="card in cards">
      <h3>{{card.user}}</h3>
      <button type="button" name="play" title="play" ng-click="toggleModal(card)">Play</button>
    </div>

  </div>

  <my-modal show='modalShown' width='250px' height='40%'>
    <h3>{{card.user}}</h3> <-- here is my problem!
  </my-modal>

// js / controllers / cards-controller.js

angular.module('angstudy').controller('CardsController', function($scope,     $http){
  $scope.cards = [];

  $http.get('http://localhost:3000/api/persons')
  .success(function(retorno){
      console.log(retorno);
  $scope.cards = retorno;
  })
  .error(function(erro) {
      console.log(erro);
  });


  $scope.modalShown = false;

  $scope.toggleModal = function(card) {
    $scope.modalShown = !$scope.modalShown;
  };
});

// js / directives / modal-dialog.js

angular.module('modalDialog', [])
.directive('myModal', function() {
  var ddo = {};

    ddo.restrict = "E";
    ddo.transclude = true;

    ddo.scope = {
        user: '@user',
        show: '='
    };

    ddo.link = function(scope, element, attrs) {
      scope.dialogStyle = {};
      if (attrs.width)
        scope.dialogStyle.width = attrs.width;
      if (attrs.height)
        scope.dialogStyle.height = attrs.height;
      scope.hideModal = function() {
        scope.show = false;
      };
    };

    ddo.templateUrl = 'js/directives/modal-dialog.html';

    return ddo;
});

// js / directives / modal-dialog.html(指令的模板)

<div class='ng-modal' ng-show='show'>
  <div class='ng-modal-overlay' ng-click='hideModal()'></div>
  <div class='ng-modal-dialog' ng-style='dialogStyle'>
    <div class='ng-modal-close' ng-click='hideModal()'>X</div>
    <div class='ng-modal-dialog-content'></div>
  </div>
</div>

// js / main.js

angular.module('angstudy', ['modalDialog']);

卡片已正常显示并且模态打开,但不显示模态中的AE值(在这种情况下,我只是测试值“user”,但json有更多数据)。如果我只插入一个静态值,它会显示...

1 个答案:

答案 0 :(得分:0)

我会通过将模态html保存在单独的文件中并使用单独的控制器来完成它,然后我将使用resolve关键字将数据传递给Modal控制器。 但由于您在两个模板上使用相同的控制器。您可以保留一个名为$ scope.SelectedCard的单独变量来实现该功能。 在您的toggleModal方法中,您可以将卡指定为:

$scope.toggleModal = function(card) {
    $scope.modalShown = !$scope.modalShown;
    $scope.selectedCard = card;
};

在模态中你可以改为:

<my-modal show='modalShown' width='250px' height='40%'>
    <h3>{{selectedCard.user}}</h3> <-- problem solved
</my-modal>