简体   繁体   中英

Span inside div doesn't apply ng-style

i am trying to Append spans in a div. Below is my div code

<div 
    id="paragraph" 
    class="paragraph"
    name="paragraph">
</div>

This is code i am implementing in my Controller

$scope.style_Text = {color:'#F00'};

for(var i = 0; i< $scope.paragraph.length; i++)
{
    var span = "<span ng-style='style_Text' id='c"+i+"'>"+$scope.paragraph[i]+"</span>";
    $( ".paragraph" ).append($(span));
    console.log(span);

}

Spans are added in the div, but style is not applied. When i copy the span from console and place it above div. This span is working fine. Style is applied on it.

I have tried putting style='color:red;' instead of ng-style, It also works.

Please help how to use ng-style here. Thank

What for u doing this? Thats bad pattern.

Your HTML:

<div 
    id="paragraph" 
    class="paragraph"
    name="paragraph">
    <span ng-repeat="elem in list">{{ elem.xxx }}</span>
</div>

In controller just add objects in your $scope.list after some action

$scope.addToList = function() {
    $scope.list.push({...}); 
}

And angular add them to DOM inside your div tag.

If you use not angular event model for refresh DOM use $scope.$apply().

  1. Do not mix jQuery to Angular, you really not need to
  2. Do all the DOM manipulation in directives!
  3. Now to your question, if you really want to it your way

You wanted this $scope.style_Text = {color:'#F00'}; to be a string I guess, so $scope.style_Text = '{color:\\'#F00\\'};' and then var span = "<span ng-style=" + $scope.style_Text + " id='c"+i+"'>"+$scope.paragraph[i]+"</span>";

But really please do a directive

Edit: in such a case like this, what is the point of using ng-style and not style itself?

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