让 ng-class 为动态创建的元素工作

Getting ng-class to work for dynamically created elements

我正在制作一个动态创建一堆标签的应用程序。每个都需要一个 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);

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

参见$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);
}

这就是我执行您提出的任务的方式;它以不同的方式利用了一些 angular 功能。我知道它不像你的问题那样使用 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/