javascript - 指令绑定(bind)中的值是正确的,但它没有返回 true

标签 javascript angularjs angularjs-directive

我从自定义指令中得到了一些奇怪的行为。如果我直接传递一个值,它似乎可以工作,但如果我传递一个值的绑定(bind),它就不起作用。另外,我 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}}">

最佳答案

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

关于javascript - 指令绑定(bind)中的值是正确的,但它没有返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25985309/

相关文章:

javascript - JS中如何指定多个对象?

javascript - 回溯历史后 Firefox 中的 Ajax 调用缓存

javascript - 我应该使用什么协议(protocol)以及它的文档是什么?

angularjs的起点在哪里如何顺序

javascript - 评估正则表达式 ng-pattern 的 AngularJS 问题

angularjs - 如何使用 Angular 访问 $http 中的 XHR?

javascript - 在 AngularJS 中创建动态指令

javascript - 在循环迭代时保留 JavaScript 数组中的双引号

javascript - AngularJS : How to bind data from dynamic url?

angularjs - 通过谷歌地图的angularjs指令重新创建 map