了解这个AngularJS指令?

时间:2018-01-04 12:08:10

标签: javascript angularjs

我有一个指令,当你正在滚动浏览页面的一部分后,它正在改变HTML类元素。我基本上只是将我在互联网上找到的代码一起破解,而我却无法理解它为什么或如何工作。我知道如果我能更好地理解它,我可以尝试为项目中更有意义的方面重新创建它。我很感激有人能给予的任何见解。以下是Angular部分:

myApp.directive('changeClassOnScroll', function ($window) {
return {
    restrict: 'A',   // What does this line do?
    scope: {
        offset: "@",   // A bit confused here
        scrollClass: "@"   // a bit confused here
    },
    link: function(scope, element) {
        angular.element($window).bind("scroll", function() { // understood
            if (this.pageYOffset >= parseInt(scope.offset)) { // understood
                element.removeClass(scope.scrollClass); // understood
                console.log('Scrolled below header.');
            } else {
                element.addClass(scope.scrollClass); // understood
            }
        });
      }
   };
})

在HTML中;

<nav change-class-on-scroll offset="100" scroll-class="navbar-transparent" class="navbar">
<!-- Don't understand why this works at all since these two elements are
<!-- not the same names as the function above? How does the directive
<!-- know to look for 'scroll-class' even tho in the directive it is
<!-- 'scrollClass' ?

对于发生的事情,我们非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

来自文档

  

在较高级别,指令是DOM元素上的标记(例如   告诉AngularJS的属性,元素名称,注释或CSS类   HTML编译器($ compile)将指定的行为附加到该DOM   元素(例如通过事件监听器),甚至转换DOM   元素及其子女。

您所写的是一个标准的angularjs代码,用于创建一个自定义指令,为您的dom添加一些功能。

  

限制:'A',//这行是做什么的?

'A'代表attribute。这意味着您可以将其用作html元素的属性,就像您用于nav一样。您可以在指令中使用以下任何限制。

A - Attribute => <div change-class-on-scroll></div>

C - Class     =>  <div class="change-class-on-scroll"></div>

E - Element   =>  <change-class-on-scroll data="book_data"></change-class-on-scroll>

M - Comment   => <!--directive:change-class-on-scroll --><br/>
  

范围:{
          offset:“@”,//这里有点困惑
          scrollClass:“@”//这里有点困惑
      },

'@'用于将html中的数据绑定到指令范围。使用offset="100",您将使值100在指令范围内可用,然后当您在链接函数中调用scope.offset时,您将获得该值。您可以使用'@','='或'&amp;'根据指令是定值,模型数据还是函数,将值绑定到指令。

  

为什么在指令中滚动类是scrollClass

它有效,因为它应该如何。通过Angularjs命名约定,要绑定的指令名称和范围对象应该在js中使用驼峰,并且应该使用html中的破折号进行编写。

答案 1 :(得分:0)

restrict: 'A', // this will restrict directive only as attribute(you can only use it as attribute or it defines directive type)
scope: {
    offset: "@", // @ means that the changes from the controller scope will be reflected in the directive scope but if you modify the value in the directive scope, the controller scope variable will not get affected.
    scrollClass: "@" 
},

答案 2 :(得分:0)

有四种类型的指令元素(E),属性(A),类名(C)和注释(M)。指令可以指定它在指令的restrict属性中支持的4种匹配类型中的哪一种定义对象。

'@'用于在指令中传递简单值。

在Html中我们不能使用驼峰案例。因此我们使用蛇壳代替骆驼箱。因此,scrollClass将被写为scroll-class。