指令绑定中的值是正确的,但它不会返回true

时间:2014-09-23 01:01:47

标签: javascript angularjs angularjs-directive

我从自定义指令中获得了一些奇怪的行为。如果我直接传入一个值似乎工作,但如果我传入绑定值,它不起作用。此外,我在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}}">

2 个答案:

答案 0 :(得分:1)

很可能您的问题可能是异步分配profile.name,当您运行该指令时,数据可能还没有回来。因此,您可以应用的一种技术是等待直到通过在范围属性(attrs.$observe)上的属性(scope.$watch)上注册监视来获取数据,并在获得值后清理监视

实施例: -

  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

答案 1 :(得分:0)

您是否尝试过以不同方式绑定范围? (虽然对我来说它既有双向作用)

//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">