How to pass a variable from $scope into a directive, and reverse?

时间:2015-09-01 23:04:53

标签: javascript jquery html angularjs angular-directive

I am currently trying to implement a directive that should make some DOM elements blink. For that, I am using $timeout to set visibility of the element to either visible or hidden. My problem is that if in the $timeout call I hard-code a value (say '500') everything runs smoothly. But if I try to pass this parameter thanks to a variable, I get the element blinking extremely fast, as if no parameter was entered (default value is '0').

HTML

<button class="btn btn-key"><span class="blink" blinkSpeed='500'>Q</span></button>
{{displayBlinkSpeed}}

JS

.directive('blink',function($timeout){
return{
    restrict:'ACE',
    transclude: true,
    scope:{
        blinkSpeed: '='
    },
    link: function(scope,element,attrs){
        function showElement(){             
            var speed = parseInt(scope.blinkSpeed);
            element.css("visibility","visible");
            $timeout(hideElement,speed);
            scope.displayBlinkSpeed = speed;
        }

        function hideElement(){
            var speed = parseInt(scope.blinkSpeed);
            element.css("visibility","hidden");
            $timeout(showElement,speed);
            scope.displayBlinkSpeed = speed;
        }

        showElement();
    },
    template: '<span ng-transclude></span>',
    replace: true
    };
});

Also, I forgot to mention that {{displayBlinkSpeed}} in the HTML is not showing anything either. My guess would be that my directive is not able to communicate (receive/send) information to the DOM. Unfortunately, I have not found a way to make it work. Have I missed/misunderstood something?

1 个答案:

答案 0 :(得分:5)

首先,{{displayBlinkSpeed}}不会显示任何内容,因为displayBlinkSpeed仅在指令的隔离范围内定义 - 它位于undefined之外。

至于blinkSpeed - 当您绑定到属性时,Angular会对属性名称进行规范化,因此scope: {blinkSpeed: "="}绑定到blink-speed="500"属性(而不是blinkSpeed="500"属性)。没有它,$scope.blinkSpeed === undefinedparseInt(undefined) === NaN会导致闪烁。

将HTML更改为:

<span class="blink" blink-speed='500'>Q</span>

有些偏离主题:

1:您不需要执行parseInt(scope.blinkSpeed),因为"="会正确解析为整数。因此,以下内容同样适用:

$timeout(hideElement, $scope.blinkSpeed);

2:,因为您不打算修改指令中的闪烁速度,与"="进行双向绑定是浪费的 - 而是单向使用绑定到"&"的表达式:

scope: {
  blinkSpeed: "&",
},
link: function(scope){
  var speed = scope.blinkSpeed();
  $timeout(hideElement, speed);
}