AngularJS:为什么我不能将DOM属性值传递给指令

时间:2021-11-19 15:12:01

Is it because I'm using $swipe?

是因为我使用$ swipe?

HTML

HTML

<div start_slide_at="459" slide-controller></div>

JS

JS

myApp.directive('slideController', ['$swipe',
    function($swipe) {

        return {
            restrict: 'EA',
            scope: {
                start_slide_at: '='
            },
            link: function(scope, element, attrs) {
                console.log(scope.start_slide_at);
            }
        }
    }
]);

It returns undefined right now :/

它现在返回undefined:/

2 个解决方案

#1


2  

well you can get the value with scope.startSlideAt variable . The "_" or "-" in the DOM attribute is converted to camel casing in the case of angularjs when double binding is used inside the direcitve . So here is your modified link function and scope attribute.

那么你可以使用scope.startSlideAt变量获取值。在direcitve中使用双重绑定时,DOM属性中的“_”或“ - ”在angularjs的情况下转换为camel大小写。所以这是你修改过的链接函数和范围属性。

     scope: {
                startSlideAt: '='
            },

    link: function(scope, element, attrs) {
                console.log(scope.startSlideAt);
              }

Hope this will solve your problem.

希望这能解决你的问题。

#2


2  

= means two way binding.

=表示双向绑定。

it's need scope variable rather than value

它需要范围变量而不是值

If you wanna just pass value then make scope

如果你想传递价值,那就制作范围

scope: {
                startSlideAt: '@'
            },

And directive convert -,_ camecase

和指令转换 - ,_ camecase

Directives have camel cased names such as ngBind. The directive can be invoked by translating the camel case name into snake case with these special characters :, -, or _

指令有诸如ngBind之类的骆驼名称。可以通过将驼峰案例名称转换为具有以下特殊字符的蛇案例来调用该指令:, - 或_

So in link

所以在链接中

console.log(scope.startSlideAt);

#1


2  

well you can get the value with scope.startSlideAt variable . The "_" or "-" in the DOM attribute is converted to camel casing in the case of angularjs when double binding is used inside the direcitve . So here is your modified link function and scope attribute.

那么你可以使用scope.startSlideAt变量获取值。在direcitve中使用双重绑定时,DOM属性中的“_”或“ - ”在angularjs的情况下转换为camel大小写。所以这是你修改过的链接函数和范围属性。

     scope: {
                startSlideAt: '='
            },

    link: function(scope, element, attrs) {
                console.log(scope.startSlideAt);
              }

Hope this will solve your problem.

希望这能解决你的问题。

#2


2  

= means two way binding.

=表示双向绑定。

it's need scope variable rather than value

它需要范围变量而不是值

If you wanna just pass value then make scope

如果你想传递价值,那就制作范围

scope: {
                startSlideAt: '@'
            },

And directive convert -,_ camecase

和指令转换 - ,_ camecase

Directives have camel cased names such as ngBind. The directive can be invoked by translating the camel case name into snake case with these special characters :, -, or _

指令有诸如ngBind之类的骆驼名称。可以通过将驼峰案例名称转换为具有以下特殊字符的蛇案例来调用该指令:, - 或_

So in link

所以在链接中

console.log(scope.startSlideAt);