1

I have few popups in my application. One is for displaying "About" and the second one for displaying contact form. What I do currently is I put the whole popup DOM into template and write custom directive like this:

angular.module('app').directive('contactForm', function() {

  return {
    restrict: 'E',
    replace: true,
    scope: {},
    templateUrl: 'contactForm.html',
    controller: function($scope) {
      $scope.submitForm = function() {
        ...  
      }
    },
    link: function(scope, el) {
      scope.$on('openContactForm', function() {
        el.show();
      });
    }
  }

});

and call such directive somewhere in my index.html

<body>
  <about-popup></about-popup>
  <contact-form></contact-form>
  ...
  ...
</body>

Somewhere on the page there is controller like this with function bound to button:

angular.module('app').controller('SideBarController', function($scope, $rootScope) {
  $scope.openContactForm = function() {
    $rootScope.$broadcast('openContactForm');
  }
});

I don't feel that's the best way of handling that, but can't figure out how to do this better. Do you have any ideas, examples?

4

1 回答 1

0

我做的最后一个应用程序需要一个简单的模式来显示消息,而我所做的方式是使用与您的指令非常相似的指令。

该指令附加模板并使用 $rootScope 来存储模态对象,该对象具有属性 show (由模板中的 ng-show 使用)和每次我需要显示/隐藏模态时调用的切换函数窗户。因为该对象位于 $rootScope 中,所以您可以在任何地方使用它。

这是该指令的简化版本。

app.directive('myModal', ['$rootScope', function ($rootScope) {
    return {
    restric: 'A',
    replace: true,
    template: '<div class="modal" ng-show="modal.show">{{ modal.mainMessage }}<br /><button ng-click="modal.toggle()">Close</button></div>',
    link: function (scope, elm, attrs) {
       $rootScope.modal= {
          mainMessage: '',
          show: false,
          toggle: function (mainMessage) {
             this.mainMessage = mainMessage;
             this.show = !this.show;
          }
       };
     }
  };
}]);

这是一个JSBin

这是一个很好的问题,我很好奇它会得到答案。

于 2013-09-09T12:08:25.573 回答