简体   繁体   English

角度指令链接函数中“ attrs”参数的用途是什么

[英]What's the use of the “attrs” parameter in an angular directive link function

Considering this directive : 考虑此指令:

.directive('myDirective', function(httpRequestTracker) {
    return {
        restrict: 'EA',
        scope: {
            myvar: "=",
        },
        link: function($scope, elem, attrs) {
            console.log($scope.myvar, attrs.myvar);
        }
    };
})

and this JS console output : 和此JS控制台输出:

> undefined undefined // if no attribute > undefined undefined //如果没有属性

> value value // if attribute value = "value" >值值//如果属性值=“值”

What is the use of the attr parameter of the link function ? link功能的attr参数有什么用? What is the difference with $scope ? $ scope有什么区别?

Thanks 谢谢

attrs is just a raw list of attributes on a directive attrs只是指令上的原始属性列表
scope is more sophisticated, you can use three different operators to populate it with values: scope更加复杂,您可以使用三种不同的运算符来为其填充值:

  • = evaluates expression in HTML, and may contain objects =评估HTML中的表达式,并且可能包含对象
  • @ interprets value passed as string. @解释以字符串形式传递的值。 always. 总是。
  • & gives you access to functions defined on parent scope &使您可以访问在父作用域上定义的函数

I know I'm quite late to the party, but for posterity's sake, the most crucial difference to me is that using scope: {...} in the directive's definition object (not the link function signature) creates an isolate scope within the directive element, whereas omitting the scope property altogether and manually retrieving values from attrs does not. 我知道我来晚了,但是为了后人,对我来说最关键的区别是在指令的定义对象(不是链接函数签名)中使用scope: {...}在指令元素,而完全省略scope属性并从attrs手动检索值则不会。 There are plenty of cases where, for whatever reason, you don't want to make a new scope but you still need the value of some attribute. 在很多情况下,无论出于何种原因,您都不想创建新的作用域,但仍然需要某些属性的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM