Shrish Shrivastava
Shrish Shrivastava

Reputation: 585

Can we use more than one objects in ng-style for a single element?

In controller we have two ng-style objects.

$scope.rightpadding = {
    paddingRight : '11px'
}



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

We want to use both these in ng-style, some thing like this

Is not working.

It can't be like

$scope.style = { paddingRight : '11px', paddingTop : '7px' } How can we achieve this?

Upvotes: 2

Views: 871

Answers (2)

Shrish Shrivastava
Shrish Shrivastava

Reputation: 585

Using angular.extend is good and its working too. But if we do not want to use it then here is another way

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,rightpadding])"> 

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You can create one method which will create an object by combining the result from multiple methods & will set it to ng-style object.

Also paddingRight should be padding-right & paddingTop should be padding-top

HTML

ng-style="setStyle()"

Code

$scope.rightpadding = function() {
  return {
    'padding-right': '11px'
  };
}

$scope.toppadding = function() {
  return {
    'padding-top': '7px'
  };
}

$scope.setStyle = function() {
  var object = {};
  angular.extend(object, $scope.rightpadding())
  angular.extend(object, $scope.toppadding())
  return object;
}

Upvotes: 2

Related Questions