简体   繁体   English

指令绑定中的值正确,但未返回true

[英]Value in directive binding is correct but it's not returning true

I'm getting some strange behavior from a custom directive. 我从自定义指令中得到了一些奇怪的行为。 If I pass in a value directly it seems to work but if I pass in a binding to a value it does not work. 如果我直接传递一个值似乎有效,但是如果我传递一个对值的绑定则无效。 Also, the value when I console.log seems to be correct but it doesn't return true. 另外,当我console.log时,该值似乎是正确的,但不会返回true。

//directive
angular.module('tallllyApp')
  .directive('userColor', ['simpleLogin', '$timeout', function (simpleLogin, $timeout) {
    'use strict';
    return {
      restrict: 'AE',
      scope: {
        color: '@'
      },
      link: function(scope, el, attrs) {
        el.css('background', '#5DC472');
        console.log(attrs); //attrs.color shows 'Andrey'
        console.log(attrs.color); //displays nothing
        console.log(attrs.color === 'Andrey'); //false
      }
    };
  }]);

//html = {{profile.name}} does output 'Andrey'    
<section class="col user-tasks" user-color color="{{profile.name}}">

Most possibly your issue could be with asynchronously assigned profile.name , by the time you run the directive the data might not have come back yet. 最有可能的问题是异步分配的profile.name ,当您运行指令时,数据可能还没有回来。 So one technique you can apply is to wait till you get the data by registering a watch on the attribute ( attrs.$observe ) of on the scope property ( scope.$watch ), and cleanup the watch once you got the value. 因此,您可以应用的一种方法是,通过在scope属性( scope.$watch )的属性( attrs.$observe )上注册手表,直到获取数据为止,并在获取值后清理该手表。

Example:- 例:-

  link: function(scope, el, attrs) {
        el.css('background', '#5DC472');

       //attrs.$observe('color', function(v){
        var unWatch = scope.$watch('color', function(v){ //Set up a watch
          if(v){ //Check if you got the value yet if so
            unWatch(); //clear the watch
            init(); //initialize directive
          }
        });

        function init(){
           console.log(attrs);
           console.log(scope.color); //attrs.color
           console.log(scope.color === 'Andrey');
        }
      }

Plnkr Plnkr

Did you try binding the scope differently, like this? 您是否尝试过像这样不同地绑定范围? (Though for me it worked both ways) (尽管对我来说,它是双向的)

//directive
angular.module('tallllyApp')
  .directive('userColor', ['simpleLogin', '$timeout', function (simpleLogin, $timeout) {
    'use strict';
    return {
      restrict: 'AE',
      scope: {
        color: '='
      },
      link: function(scope, el, attrs) {
        el.css('background', '#5DC472');
        console.log(scope.color); //should display 'Andrey'
      }
    };
  }]);

//html = {{profile.name}} does output 'Andrey'    
<section class="col user-tasks" user-color color="profile.name">

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

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