2014-09-23 6 views
0

사용자 지정 지시문에서 이상한 동작이 나타납니다. 값을 직접 전달하면 작동하는 것처럼 보이지만 값에 바인딩을 전달하면 작동하지 않습니다. 또한, 내가 console.log 때 올바른 값을 true로 반환하지 않습니다. 비동기 적 데이터가 아직 돌아 오지 않았을 수 있습니다 지시어를 실행 시간, profile.name 할당과지시문 바인딩의 값은 정확하지만 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}}"> 

답변

1

대부분의 가능성이 문제가 될 수 있습니다. 따라서 적용 할 수있는 한 가지 기법은 범위 속성 (scope.$watch)에있는 속성 (attrs.$observe)의 시계를 등록하고 데이터를 가져올 때까지 기다린 다음 값을 얻은 후 시계를 정리하는 것입니다.

예 : -

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

+0

정확합니다. 이 비동기 작업을 처리하는 것은 어렵습니다. 특별히 각도에 대한 권장 판독 값은 무엇입니까? – EmptyPockets

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"> 
+0

나는 이것을 시도했다. 그것은 비동기 profile.name 때문이었습니다. 내가 이해하는 한 범위에서 메서드를 실행해야 할 때 '='이 사용됩니다. 나는 그것에 관한 egghead.com 비디오를 보았다. 그러나 그들은 나의 특별한 경우를 포함하지 않았다. – EmptyPockets

+0

지시문과 데이터를 실제로 어떻게 사용하고 있는지 잘 모르겠지만 일반적으로 범위 데이터를 템플릿에 직접 삽입하면 값이로드 될 때마다 각도가 자동으로 데이터를 채 웁니다. 지시어의 링크 메소드에있는 값에 액세스해야하는 경우 자신 만의 감시자를 설정해야합니다. – ryansilva

관련 문제