在附加语句Angular JS中插入ng-click

时间:2019-02-13 14:45:03

标签: angularjs

  for(var i = 0 ; i<data.success.length; i++)
            {
              // console.log(data.success[i]);

                  $("#show_rules").append("<li style='display: flex;'><div class='checkbox' id='container_divv'><a id='mm'ng-click='edit_initial_infoq()' >"+data.success[i].name+"</a><button ng-click='edit_initial_infoq()'>dd</button></div></li>");


            }
            })

            };
                         $scope.edit_initial_infoq= function(){
                         console.log('edit_initial_infoq');
                             };

这没有给我错误并且无法处理edit_initial_infoq函数

1 个答案:

答案 0 :(得分:0)

我认为问题在于您要附加到html上,而angular没有意识到所做的更改,因此ng-click无法正常工作。请尝试以下操作:

代替:

var html = "<li style='display: flex;'><div class='checkbox' id='container_divv'><a id='mm' ng-click='edit_initial_infoq()'>"+data.success[i].name+"</a><button ng-click='edit_initial_infoq()'>dd</button></div></li>";
#("#show_rules").append(html);

尝试做:

var html = "<li style='display: flex;'><div class='checkbox' id='container_divv'><a id='mm' ng-click='edit_initial_infoq()'>"+data.success[i].name+"</a><button ng-click='edit_initial_infoq()'>dd</button></div></li>";
var myElement = angular.element( document.querySelector( '#show_rules' ) );
myElement.append( $compile(html)($scope) );

但是...您不应该这样做。您不应在执行操作时在控制器内部操纵DOM。相反,请尝试执行以下操作:

JavaScript

YourService.loadRules().then(function(data){
    $scope.rules = data.success;
});

HTML

<ul id="show_rules">
    <li ng-repeat="rule in rules" style='display: flex;'>
        <div class='checkbox' id='container_divv'>
            <a id='mm' ng-click='edit_initial_infoq()'>
                {{rule.name}}
            </a>
            <button ng-click='edit_initial_infoq()'>dd</button>
        </div>
    </li>
</ul>

这是一个很棒的SO问题,第一个答案载有重要信息:"Thinking in AngularJS" if I have a jQuery background?