【问题标题】:How to Insert HTML with angularJS attribute in javascript?如何在 javascript 中插入带有 angularJS 属性的 HTML?
【发布时间】:2017-09-22 02:36:42
【问题描述】:

我想试试:

function test(){
   $('#somediv').html('<div ng-model="name">{{name}}</div>');
}

有没有办法做到这一点?

【问题讨论】:

  • jQueryish DOM 操作对于 Angular 来说不是一个好习惯。您可以使用 ng-show/hideng-if 来代替

标签: javascript html angularjs inject


【解决方案1】:

当你添加包含 angular 内置指令的 html 时,你必须通过$compile 重新编译它才能让 angular 识别。

参考下面的代码sn-p。

angular.module("app", [])
  .controller("myCtrl", function($scope, $compile) {
    $scope.name = 'test value';
    $scope.test = function() {
      var element = angular.element($('#somediv'));
      element.html('<div ng-model="name">{{name}}</div>');
      $compile(element)($scope);
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <input type="text" ng-model="name">
  <button ng-click="test()">Add</button>
  <div id="somediv"></div>
</div>

【讨论】:

    【解决方案2】:

    您需要使用$compile 服务。

    只需像这样编译html字符串:

    var html = $compile('&lt;div ng-model="name"&gt;{{name}}&lt;/div&gt;')($scope);

    不要忘记将$compile 服务注入您的控制器。

    【讨论】:

    • 感谢 Hasan Ibrahim,我尝试在我的角度控制器中做同样的想法,但出了点问题:(stackoverflow.com/questions/43603948/…
    • @NhạHoàng 也接受这个。因为这是要走的路:)
    【解决方案3】:

    不要在 Angular 中使用 jQuery DOM 操作,而是执行以下操作:

    angular.module("main", []).controller("mainController", function($scope){
    
      $scope.toggle = function(){
      
        $scope.show = !$scope.show;
      
      }
    
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
    <html ng-app="main"> 
    <head> </head>
    
    
    <body ng-controller="mainController">
    <div>
    <button ng-click="toggle()"> Toggle Div </button>
    
    
    <div ng-if="show"> Div Contents </div>
    </div>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      相关资源
      最近更新 更多