简体   繁体   中英

Retrieve css values in Angular JS directives

I am a Angular JS newbie and I try to write some encapsulated directives to style button groups. I have an " restrict: 'A' " directive in which I need to retrieve the parent's padding to get the usable with within. I also try to avoid JQuery. Angular JS looks pretty neat and I don't want to mess up this feeling. Briefly my link function contains the following:

parentScope = element.parent().scope();
parentScope.$watch(parentHeight = element.parent()[0].css("padding"), function(newValue, oldValue, scope){
   var parentHeight = element.parent()[0].offsetWidth,
   parentPadding = newValue;
}

I keep getting an undefined error. What is the proper way to access css values in directives?

$watch should be given a name of member of scope (which is string), or function ( https://docs.angularjs.org/api/ng/type/$rootScope.Scope ). If it is member name it will react to its change, if it is function it will react to change of its return value. result of assign is assigned value, so you are actually passing value of padding at specific moment to watch, while you should pass a member name or function. You should instead pass a function that returns value of padding, like this:

parentScope.$watch(
  function() { 
    return element.parent()[0].css("padding"); 
  }, function(newValue, oldValue, scope) {
    var parentHeight = element.parent()[0].offsetWidth,
    parentPadding = newValue;
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM