Home > Blockchain >  How to populate ng-style with object of CSS
How to populate ng-style with object of CSS

Time:12-26

I have built an object of CSS that I've defined the CSS property name and value. The goal is to build out a form to manipulate the value and automatically update the CSS on the page visually for the user.

I have it all working except for an elegant way to actually style the item in real time.

Here is the link to example https://codepen.io/uncommonjoe/pen/KKXyzBp

This is the object I created that I'm working with

vm.card = [
        {
            class: "card",
            properties: [
                {
                    name: "background-color",
                    value: "#FFFFFF"
                },
                {
                    name: "border",
                    value: "1px solid #FFFFFF"
                },
                {
                    name: "border-radius",
                    value: "5px"
                },
                {
                    name: "box-shadow",
                    value: "0 0 26px rgb(0 0 0 / 20%)"
                },
                {
                    name: "margin",
                    value: "0"
                },
                {
                    name: "padding",
                    value: "0"
                }
            ]
        }
    ];

And in the HTML I'm using ng-repeat to build out form controls

<div ng-repeat="card in vm.card">
    <b>{{card.class}}</b>
    <div ng-repeat="object in card.properties">
        <label>{{object.name}}</label>
        <input type="text" ng-model="object.value" />
    </div>
</div>

This is the example of the item. As you can see, that's not dynamic and reusable.

 <div  style="width: 18rem;"
    ng-style="{
        'background-color': vm.card[0].properties[0].value,
        'border': vm.card[0].properties[1].value,
        'border-radius': vm.card[0].properties[2].value,
        'box-shadow': vm.card[0].properties[3].value,
        'margin': vm.card[0].properties[4].value,
        'padding': vm.card[0].properties[5].value,
    }">
    <div >
        <h5 >Card title</h5>
        <p >Some quick example text to build on the card title and make up the bulk of the card's content.</p>
        <a href="#" >Go somewhere</a>
    </div>
</div>

I need a good way to do an ng-repeat so to speak in the ng-style and pull the name and define that as the CSS property and value as the value.

CodePudding user response:

Define a styler function in your controller and then call it from ng-style:

vm.styler=function(props){
    var styles={};
    props.forEach(css=>{
        styles[css.name]=css.value
    })
    return styles;
}

and in ng-style: ng-style="vm.styler(vm.cardObj[0].properties)"

  • Related