让ng-class适用于动态创建的元素

时间:2015-07-14 02:29:11

标签: angularjs dynamically-generated ng-class

我正在创建一个动态创建一堆标签的应用程序。每个都需要一个ng-class参数,但Angular不会看到新创建的元素,因此会被忽略。 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);

如何让它识别新创建的元素?

2 个答案:

答案 0 :(得分:2)

$compile。您可以使用此服务:

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);
}

答案 1 :(得分:2)

这就是我执行你所呈现的任务的方式;它使用不同的角度特征。我知道它不会像你的问题那样使用angular.element,但它通常更灵活。以下是相关代码:

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"});
    }
}

和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/