dreed75
dreed75

Reputation: 115

Getting ng-class to work for dynamically created elements

I am making an application that dynamically creates a bunch of labels. Each one needs an ng-class parameter but Angular doesn't see the newly created elements and so it is ignored. http://jsfiddle.net/vdkuqhg7/

var myEl = angular.element( document.querySelector( '#box' ) );
var div = angular.element('<div ng-class=\"{\'red\' : areaStatus, \'green\' : !areaStatus}\">This is more text</div>');
myEl.append(div);

How do I get it to recognize the newly created elements?

Upvotes: 1

Views: 3242

Answers (2)

Claies
Claies

Reputation: 22323

This is how I would perform the task you have presented; it utilizes some angular features differently. I understand that it doesn't use angular.element as your question does, but it is generally more flexible. Here is the relevant code:

myModule.controller('myController', function ($scope) {

    $scope.areaStatus = false;

    $scope.dynamicData = [];

$scope.insertDiv=function(message) {
    if (message)
    {
        $scope.dynamicData.push({value : message})
    }
    else{
    $scope.dynamicData.push({value: "This is more text"});
    }
}

and the HTML:

<div ng-controller="myController" id="box">
        <button ng-click="areaStatus = !areaStatus">Toggle</button>
        <div ng-class="{'red' : areaStatus, 'green' : !areaStatus}">
            This is some text
        </div>

<button ng-click="insertDiv()">insert</button>
<button ng-click="insertDiv('This is a different Message')">insert different message</button>

<div ng-repeat="data in dynamicData" ng-class="{'red' : areaStatus, 'green' : !areaStatus}">
    {{data.value}}
</div>

http://jsfiddle.net/mkv4y340/

Upvotes: 2

Hayden
Hayden

Reputation: 2112

See $compile. You can use this service similarly to this:

http://jsfiddle.net/haydenk/vdkuqhg7/1/

var myModule = angular.module('myModule', []);

myModule.controller('myController', function ($scope, $compile) {

    $scope.areaStatus = false;


$scope.insertDiv=function() {
    var myEl = angular.element( document.querySelector( '#box' ) );
    var div = angular.element('<div ng-class=\"{\'red\' : areaStatus, \'green\' : !areaStatus}\">This is more text</div>');
        myEl.append(div);
        $compile(div)($scope);
}

Upvotes: 2

Related Questions