从Angular指令访问元素样式

时间:2013-07-09 17:27:49

标签: angularjs

我确信这将是“不要那样做!”但我试图在角形元素上显示样式。

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

4 个答案:

答案 0 :(得分: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 :(得分:1)

尤里卡!

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

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);

所以这需要大量的持久性和猜测。也许超时是不必要的,但在调试时,我似乎只在超时发生后从父级获得了样式值。

此外,我不确定为什么,但我必须通过parentElement来获取样式(即使它实际上是继承的(耸肩)?)

再次更新小提琴

没有超时,但只是查看了样式的parentElement,它似乎仍然有效,所以抓住了对完全不可用的样式的怀疑,它只是在我期望的地方不可用。

同样神圣的牛有很多方法可以在Chrome中进行调试: https://developers.google.com/chrome-developer-tools/docs/javascript-debugging

我用过

debugger;

代码中的语句,用于删除断点而无需搜索所有小提琴文件。

再次快速更新

下面的代码来自AngularUI团队的Boostrap-UI,声称提供了观察相应事件的方法(没有尝试过,但看起来应该有所帮助)。

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

/**
 * $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;
}]);

答案 2 :(得分:1)

您将面临的问题是getComputedStyle被认为是一种运行速度非常慢的方法,因此如果使用它会遇到性能问题,特别是如果您希望angularjs在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;
            });
        }
    }
});

答案 3 :(得分:0)

如果您不必在子元素上使用该指令,则此解决方案有效。如果您只是将声明放在ng-repeat元素本身上,那么您的解决方案就可以运行:

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

Fiddle