How can I use multiple ng-style objects for one element in AngularJS

I have two objects ng-stylein my controller.

$scope.leftpadding = {
    paddingLeft : '7px'
}

$scope.toppadding = {
    paddingTop : '7px'
}

I want to use both of these objects in ng-style, for example

<h5 ng-style="toppadding leftpadding"> 

Does not work. since none of the objects are applied in style.

It can't be like

$scope.style = {
  paddingLeft : '7px',
  paddingTop : '7px'
}

Is there any way to achieve this?

+4
source share
2 answers

Create a generic method in scope

$scope.margeStyleObj = function(objectList) {
    var obj = {};
    objectList.forEach(function(x) {
      for (var i in x)
        obj[i] = x[i];
    });
    return obj;
  }

Then call from html

<h5 ng-style="margeStyleObj([toppadding,leftpadding])"> 

JSFIDDLE

You can also use angular.extend

Like this

  $scope.margeStyleObj = function(objectList) {
    var obj = {};
    objectList.forEach(function(x) {
        angular.extend(obj,x);
    });
    return obj;
  }

JSFIDDLE

+3
source

I am not sure what you can use ngStylethis way. Try the following:

ng-style="{'padding-top': paddingTop, 'padding-bottom': paddingBottom}" 

$scope.paddingTop padding-top, padding-bottom.

+2

Source: https://habr.com/ru/post/1621207/


All Articles