2013-07-09 3 views
3

나는 이것이 "그렇게하지 않을 것"이라고 확신합니다. 하지만 각도 요소에 스타일을 표시하려고합니다.각도 지시어에서 액세스 요소 스타일

<div ng-repeat="x in ['blue', 'green']" class="{{x}}"> 
     <h3 insert-style>{{theStyle['background-color']}}</h3> 
</div> 

결과는 기본적으로 내가 스타일 속성을 검색하고이를 표시해야

<div class='blue'><h3>blue(psudeo code hex code)</h3></div> 
<div class='green'><h3>green(psudeo code hex code)</h3></div> 

될 것이다.

지침 코드 ...

directives.insertStyle = [ function(){ 
    return { 
     link: function(scope, element, attrs) { 
      scope.theStyle = window.getComputedStyle(element[0], null); 
     } 
} 
}]; 

바이올린 예 : 당신은 자식 요소에 대한 지침을 가지고이없는 경우 http://jsfiddle.net/ncapito/G33PE/

+1

컨트롤러로하지 마세요! 지시문을 사용하십시오! –

+0

그래서 제안 사항은 스타일 값을 삽입하는 지시문을 만드는 것입니다. – Nix

+0

지시문에 동의하십시오. – rGil

답변

6

내가 obj를 전체를 사용할 때 작동 작동하지 않았다 하나의 소품을 사용하지만, 내 최종 솔루션 (

마크 업 ...) 잘

<div insert-style class="box blue"> 
    <h4 > {{ theStyle['color'] | toHex}} </h4> 
</div> 

지침

directives.insertStyle = [ "$window", function($window){ 
    return { 
     link: function(scope, element, attrs) { 
      var elementStyleMap = $window.getComputedStyle(element[0], null); 
      scope.theStyle = elementStyleMap 
     } 
    } 
}]; 
+1

이 크로스 브라우저입니까? –

0

이 솔루션은 작동합니다. 방금 NG-반복 요소 자체에 선언을 배치하면, 솔루션 작동 :

<div insert-style ng-repeat="x in ['blue', 'green']" class="{{x}}"> 

Fiddle

+0

제 바이올린을 보아주세요, * 스타일 *을 얻으려고합니다. 나는 그것을 어리석게했다. – Nix

+0

그래서 나는 네가 왜 작동하는지, 더 복잡한 해결책이 없는지 알아 냈다. 왜냐하면 지시문에서 사용자가 지정한 스타일을 반환했기 때문이다. 귀하의 경우/내 예제에서는, getComputedStyle을 처리 할 시간이있는 뷰로 맵을 반환했습니다. – Nix

1

유레카!

var leanwxApp = angular.module('LeanwxApp', [], function() {}); 

var controllers = {}; 
var directives = {}; 
directives.insertStyle = [ function(){ 
    return { 
     link: function(scope, element, attrs) { 
      scope.theStyle = window.getComputedStyle(element[0].parentElement, null) 
     } 
} 
}]; 

leanwxApp.controller(controllers); 
leanwxApp.directive(directives); 

http://jsfiddle.net/G33PE/5/

그래서 그것은 단지 지속성과 추측을 많이했다. 아마도 타임 아웃은 불필요하지만 디버깅 중에는 타임 아웃이 발생한 후 부모로부터 스타일 값만 얻은 것처럼 보였습니다. 하지만 스타일을 얻기 위해 parentElement까지 가야했다 왜

또한 잘 모르겠어요 (그것은 현실적으로) (어깨를 으쓱를 상속 될 것이라고하더라도?)

업데이트 바이올린 다시

타임 아웃이 없지만 스타일에 대한 parentElement 만 보았는데 여전히 작동하는 것처럼 보이기 때문에 스타일에 대한 의문은 전혀 사용 가능하지 않습니다. 예상 할 수없는 곳에서 사용할 수 없습니다. https://developers.google.com/chrome-developer-tools/docs/javascript-debugging

내가 모든 바이올린 파일을 검색 할 필요없이 브레이크 포인트에서 드롭 코드에

debugger; 

문을 사용 :

또한 거룩한 소 크롬에서 디버깅하는 방법은 여러가지가 있습니다.

하나 더 빠른 업데이트는

아래의 코드는 AngularUI 팀에서 부트 스트랩 - UI에서 제공하고 적절한 이벤트를 볼 수있는 수단을 제공하는 주장 (이 시도하지 않은 있지만해야 것 같습니다 도움).

/** 
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete. 
* @param {DOMElement} element The DOMElement that will be animated. 
* @param {string|object|function} trigger The thing that will cause the transition to start: 
* - As a string, it represents the css class to be added to the element. 
* - As an object, it represents a hash of style attributes to be applied to the element. 
* - As a function, it represents a function to be called that will cause the transition to occur. 
* @return {Promise} A promise that is resolved when the transition finishes. 
*/ 
.factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) { 

    var $transition = function(element, trigger, options) { 
    options = options || {}; 
    var deferred = $q.defer(); 
    var endEventName = $transition[options.animation ? "animationEndEventName" : "transitionEndEventName"]; 

    var transitionEndHandler = function(event) { 
     $rootScope.$apply(function() { 
     element.unbind(endEventName, transitionEndHandler); 
     deferred.resolve(element); 
     }); 
    }; 

    if (endEventName) { 
     element.bind(endEventName, transitionEndHandler); 
    } 

    // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur 
    $timeout(function() { 
     if (angular.isString(trigger)) { 
     element.addClass(trigger); 
     } else if (angular.isFunction(trigger)) { 
     trigger(element); 
     } else if (angular.isObject(trigger)) { 
     element.css(trigger); 
     } 
     //If browser does not support transitions, instantly resolve 
     if (!endEventName) { 
     deferred.resolve(element); 
     } 
    }); 

    // Add our custom cancel function to the promise that is returned 
    // We can call this if we are about to run a new transition, which we know will prevent this transition from ending, 
    // i.e. it will therefore never raise a transitionEnd event for that transition 
    deferred.promise.cancel = function() { 
     if (endEventName) { 
     element.unbind(endEventName, transitionEndHandler); 
     } 
     deferred.reject('Transition cancelled'); 
    }; 

    return deferred.promise; 
    }; 

    // Work out the name of the transitionEnd event 
    var transElement = document.createElement('trans'); 
    var transitionEndEventNames = { 
    'WebkitTransition': 'webkitTransitionEnd', 
    'MozTransition': 'transitionend', 
    'OTransition': 'oTransitionEnd', 
    'transition': 'transitionend' 
    }; 
    var animationEndEventNames = { 
    'WebkitTransition': 'webkitAnimationEnd', 
    'MozTransition': 'animationend', 
    'OTransition': 'oAnimationEnd', 
    'transition': 'animationend' 
    }; 
    function findEndEventName(endEventNames) { 
    for (var name in endEventNames){ 
     if (transElement.style[name] !== undefined) { 
     return endEventNames[name]; 
     } 
    } 
    } 
    $transition.transitionEndEventName = findEndEventName(transitionEndEventNames); 
    $transition.animationEndEventName = findEndEventName(animationEndEventNames); 
    return $transition; 
}]); 
+0

신뢰할 수 있다고 말하면서, 나는 바이올린을 어리 석고 자식을 제거했습니다. 그리고 그것은 작동하지 않습니다. http://jsfiddle.net/ncapito/MVesL/ 부모님 께가는 것은 이상한 일을하고 있습니다. – Nix

+1

나는 이상하게도 이상하게 여기지 않는다는 것에 동의하지만 적어도 어떤 종류의 대답을 얻었으므로 무슨 일이 일어나고 있는지 전혀 알지 못해 흥분했다. 당신이 진짜 해결책을 찾길 바랍니다. 나는 행운을 빈다. – shaunhusain

1

http://angular-ui.github.io/bootstrap/

것을 사용하는 경우 성능 문제로 실행됩니다, 그래서 당신이 볼 때마다를 업데이트 AngularJS와 원하는 특히, getComputedStyle이 매우 느리게 실행 방법 간주됩니다 직면하게 될 문제 getComputedStyle이 변경됩니다.

또한 getComputedStyle은 가능한 모든 단일 스타일 선언을 해결합니다. 이는별로 유용하지 않을 것입니다. 그래서 가능한 스타일의 수를 줄이는 방법이 필요하다고 생각합니다.

은 확실히이 안티 패턴을 고려,하지만 당신은 여전히이 어리 석음에서 주장하는 경우 :

module.directive('getStyleProperty', function($window){ 
    return { 
     //Child scope so properties are not leaked to parent 
     scope : true, 
     link : function(scope, element, attr){ 
      //A map of styles you are interested in 
      var styleProperties = ['text', 'border']; 
      scope.$watch(function(){ 
       //A watch function to get the styles 
       //Since this runs every single time there is an angularjs loop, this would not be a very performant way to do this 
       var obj = {}; 
       var computedStyle = $window.getComputedStyle(element[0]); 
       angular.forEach(styleProperties, function(value){ 
        obj[value] = computedStyle.getPropertyValue(value); 
       }); 
       return obj; 
      }, function(newValue){ 
       scope.theStyle = newValue; 
      }); 
     } 
    } 
}); 
관련 문제