AngularJs - 我应该如何分离模式窗口?

标签 angularjs angularjs-directive

所以我已经使用 AngularJS 相当长的时间了,但仍然需要了解指令背后的场景。

我正在尝试构建一个指令,根据需要附加模式窗口,并在不再需要时将其与 DOM 分离。

所以我这样做了:

    app.directive('myDirective',function($document){

    return{

        restrict: 'E',
        templateUrl: 'partials/modules/template.html',
        link: function($scope,$element){

            var body = $document.find('body').eq(0);

            $element.remove();            

            $scope.create = function(){                 
               body.append($element);                   
            };

        }

    }

});

并且发现这会导致 View 和 Controller 之间失去链接。

到目前为止,情况很糟糕。

但是我在这里缺少什么基本概念?实现这一目标的正确方法是什么?

我脑子里有一些凌乱(而且古怪)的选项,包括

  • 使用ng-show
  • 手动设置隐藏 CSS 类
  • 追加后将内容重新链接在一起

它们对我来说看起来很奇怪而且完全错误,而且我特别不想使用样式属性来做到这一点。

我也不想使用 Angular-UI 的模态模块。

最佳答案

您绝对应该重新考虑您对使用样式属性的看法。这是 Angular 推荐的方法:

'AngularJS 的主要设计目标之一是允许应用程序开发人员在很少或根本不直接操作 DOM 的情况下构建 Web 应用程序。在许多情况下,这也会导致更具声明性的编程风格。这使得业务逻辑可以轻松地进行单元测试,并大大提高您开发应用程序的速度。' What is the AngularJS way to show or hide a form element?

我经常做这种事。在我看来,使用 ng-class 和 json 是最简单的方法,也是最简单的测试方法。这是一个粗略的想法。另外,您不需要将元素附加到正文,这就是链接阶段的全部目的:

app.directive('myDirective',function($document){

return{

   restrict: 'E',
   templateUrl: '<div myDirective ng-class="{\'hideClass\':object.hide===true, \'showClass\':object.show===true "></div>',
   link: function($scope,$element){

      scope.element= {hide:false, show:true}          

      if(someCondition) {
         scope.element.hide = true;
      }
      if (anotherCondition) {
         scope.element.show = true;
      } 

    }

  }

});

然后,在您的测试中:

it('should be hidden if...', function () {
   angular.mock.inject(function ($compile, $rootScope) {
      var scope = $rootScope.$new();
      var elem = $compile('<div myDirective></div>')(scope);
      // ... some conditional code to manipulate scope.element json, you may need timeout to wait for DOM to load so you can check that the class is present            
      expect(elem.hasClass('hideClass')).toBe(true);
    });
});

关于AngularJs - 我应该如何分离模式窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22662180/

相关文章:

javascript - 在链接内使用监视会导致无限的摘要循环。

javascript - Angular - 基于模型创建指令

javascript - 如何利用 AngularJS 指令的功能将渲染内容推迟到单击事件发生?

AngularJS : access scope object from parent to child

angularjs - 检测 Angular 指令中不可分配的值

javascript - 我的 React 组件是否被重新创建而不是更新?

javascript - 使用 ng-pattern 识别 Angular 字母数字字段中的前导零

javascript - 创建用于更改表单占位符文本的 Angular Directive(指令)

javascript - 如何从 Angular JS Controller 获取 JSON 数据

javascript - 安装 ng-mouseover 和 ng-mouseout 会导致 AngularJS 代码效率极低