将字符串解析为DOM,ng-click不起作用

时间:2015-12-27 13:19:18

标签: javascript html angularjs

我尝试在" #text"中创建n个按钮,在ng-click上创建按钮()。当我打电话给" loadButtons(n)"功能,按钮显示,但点击nothings发生... 测试按钮完美运行...... 我认为它与从字符串到DOM的解析有关,但我不知道如何做得更好...... :(

html的

<div id="test">
   <button class="button button-full button-light" ng-click="button();">Test</button>
</div>

<div id="text"></div>

的.js

$scope.button = function () {
    console.log("BUTTON");
};

//Load n buttons in #text
$scope.loadButtons = function (n) {
    var content = "";
    for (var i = 0; i < n; i++) {
        content = content.concat('<button class="button button-full button-light"' 
        +'ng-click="button();">' + i + '</button>');
    }
    $('#text').html(content);
}

1 个答案:

答案 0 :(得分:2)

您应该使用ng-repeat指令,如下所示

<div id="test">
   <button 
       class="button button-full button-light" 
       ng-repeat="i in getNumber(maxButtons) track by $index"
       ng-click="testButton(i)"
       >
       {{i}}
   </button>
</div>

在您的控制器中,您可以拥有以下代码:

    $scope.maxButtons= 10;
    $scope.getNumber = function(num) {
       return new Array(num);   
    }
    $scope.testButton = function(val){
       console.log(val);
    }

开始以Angular方式思考:)