What is the AngularJS way of handling a modal like this

后端 未结 1 788
抹茶落季
抹茶落季 2020-12-24 09:17

I know you\'re not supposed to put your display logic inside of a controller and I\'m struggling with the proper AngularJS way to approach this.

I\'m presenting for

相关标签:
1条回答
  • 2020-12-24 09:50

    You don't want to manipulate the DOM (or even reference it) from your controllers.

    A directive is best here.

    app.directive('revealModal', function (){
       return function(scope, elem, attrs) {
         scope.$watch(attrs.revealModal, function(val) {
            if(val) {           
               elem.trigger('reveal:open');
            } else {
               elem.trigger('reveal:close');
            }
         });
         elem.reveal();
       }
    });
    

    then in your controller:

    $scope.modalAddWidget = function (){
       $scope.ui = { add_widget_value: '' };
       $scope.showModal = true;
    };
    
    $scope.addWidget = function (){
        $scope.myobject.widgets.push({"name": $scope.ui.add_widget_value});
        $scope.ui.add_widget_value = '';
        $scope.showModal = true;
    };
    

    And in your HTML

    <div class="button" ng-click="modalAddWidget()">Add Widget</div>
    <div id="modalAddWidget" class="reveal-modal" reveal-modal="showModal">
      <h6>New Widget</h6>
      <form name="addWidgetForm" ng-submit="addWidget()">
        <fieldset>
          <legend>Widget Name</legend>
          <input type="text" name="widgetValue" ng-model="ui.add_widget_value" required />
          <span ng-show="addWidgetForm.widgetValue.$error.required">required</span>
        </fieldset>
        <button type="submit" class="small button right">Add Widget</button>
        <div class="small button right secondary" ng-click="showModal = false;">Cancel</div>
      </form>
    </div>
    

    Basically you'd set a boolean in your scope to show and hide your modal. (I'm not sure of reveal modal's open/close mechanism, so I'm guessing in my code above).

    ALSO: I went through the effort of adding some validation in there.

    0 讨论(0)
提交回复
热议问题