Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two ng-style objects in my controller.

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

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

I want to use both these objects in ng-style like

<h5 ng-style="toppadding leftpadding"> 

Is not working. as neither of the objects are being applied in style.

It can't be like

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

Is there any way to achieve this?

like image 288
Aditya Ponkshe Avatar asked Dec 22 '15 05:12

Aditya Ponkshe


2 Answers

Create a common 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

like image 194
Anik Islam Abhi Avatar answered Nov 15 '22 03:11

Anik Islam Abhi


I am not sure you can use ngStyle in that way. Try this:

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

And have $scope.paddingTop to have whatever value you want for padding-top, padding-bottom.

like image 35
Tarun Dugar Avatar answered Nov 15 '22 04:11

Tarun Dugar