AngularJS模态窗口数据/对象流

AngularJS modal window data/object flow

本文关键字:对象 数据 模态 窗口 AngularJS      更新时间:2023-09-26

我创建了一个小演示,当我需要在 Angular 中打开模态窗口时使用。使用指令作为模式窗口模板。

不确定的是我将数据/函数传递给模态的方式。

开口控制器:

    $scope.openModal = function($event){
       $scope.items = [1,2,3,4,5];
       $scope.modalInstance =  $modal.open({
           template: '<modalwindow></modalwindow>',
           scope:$scope,
           test:'akex'
    });
    $scope.modalInstance.result.then(function (selectedItem) {
        console.info(selectedItem);
    }, function () {
        console.info('Modal dismissed at: ' + new Date());
    });

和模态指令:

 angular.module('angModalApp')
 .directive('modalwindow', function () {
   return {
      templateUrl: 'scripts/directives/modalwindow.tmpl.html',
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
          scope.ok = function () {
              scope.modalInstance.close(["a","b","c"]);
          };
          scope.cancel = function () {
              scope.modalInstance.dismiss('cancel');
          };
  }
};
});

我要问的是你们对模态的这种使用有何看法。有没有更好的方法?

谢谢你的时间。

该项目的来源可以在以下位置找到: https://github.com/trostik/angular-modal-window-demo

我建议您使用Angular-UI/bootstrap:http://angular-ui.github.io/bootstrap/

它易于实现且稳定。

将数据

传递到此类指令的最佳方法通常是通过隔离作用域

取自 http://docs.angularjs.org/guide/directive:

<!doctype html>
<html ng-app="docsIsolateScopeDirective">
  <head>
    <script src="http://code.angularjs.org/1.2.0-rc.3/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <div ng-controller="Ctrl">
      <my-customer customer="naomi"></my-customer>
      <hr>
      <my-customer customer="igor"></my-customer>
    </div>
  </body>
</html>

请注意他们如何使用指令 myCustomer 上的自定义属性从控制器 Ctrl 的作用域传入数据。

要访问此数据,指令定义应使用 scope 选项:

  .directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customer: '=customer'
    },
    templateUrl: 'my-customer.html'
  };
});

您可以看到如何在范围内指定客户。值 = customer 告诉 Angular 在指定为属性的数据与指令的隔离作用域(定义为 customer)的属性之间创建双向数据绑定。您也可以只指定 = 以获得更短的方法,在这种情况下,它将在指令的作用域上创建与属性名称相同的引用。如果需要传入数据不应在指令内更改,则应使用@ 符号而不是 =,如果需要传入函数,则应使用 & 符号。