What is the AngularJS way of handling a modal like this

后端 未结 1 795
抹茶落季
抹茶落季 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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

    Add Widget
    New Widget
    Widget Name required
    Cancel

    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)
提交回复
热议问题