Angular JS:使用动态添加的html元素进行数据绑定

时间:2017-05-12 07:45:56

标签: javascript jquery html angularjs

我在角度js中遇到双向数据绑定问题。这是示例代码。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body ng-app="">

<div>

<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p>

<div id="jack">
</div>
<script>
    $("document").ready(function(){
        $("#jack").append("<p ng-bind='name'></p>");
    });
</script>
</body>
</html>

在这里我使用jQuery动态地将一个带有ng-bind的段落添加到名为jack的div中

由于某种原因,当我在输入框中输入内容时,它没有反映在带有ng-bind属性的段落中。

我是角度js的新手,并会要求您提供一个简单的解决方案来解决这个问题。

2 个答案:

答案 0 :(得分:1)

您无法使用jQuery以这种方式修改Angular之外的DOM。 Angular不知道该绑定,因为它不是由Angular编译的。

要解决此特定示例,只需删除jQuery脚本并将HTML更改为:

<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>

上面的例子可行,但我想这不是一个真实的例子。如果您发布更具体的方案,我可以更新我的答案以帮助您解决问题。

修改

根据你的评论,我会创建一个简单的指令,你可以传递你的模板,它会编译模板并将编译的模板注入DOM。

指令:

function myTemplateCompile($compile) {

  return {
    restrict: 'E',
    link: link
  }

  function link(scope, elem, attrs) {

    attrs.$observe('template', (template) => {
      elem.html(template);
      $compile(elem.contents())(scope);
    });

  }

}

HTML

<my-template-compile template="any HTML you might need including bindings"></my-template-compile>

然后,您可以动态更改指令的模板属性,它将根据新值重新编译和更新DOM。

上面的例子应该指出你正确的方向。我只需要警告你,这可能非常危险。如果您注入的内容来自某些用户输入,则可能会产生非常严重的安全隐患。请确保您没有将您的应用程序暴露给攻击。

答案 1 :(得分:0)

首先,我们需要定义应用程序并创建自定义指令。

var myApp=angular.module('myApp',[])
                 .controller('myCtrl',function($scope){
                      $scope.name="Your name";   
                 })
   myApp.directive('myDirective', function() {
         return {
                 restrict: 'E',
                 template: '<span data-ng-bind="name"></span>'
         };
   });

在此之后你需要使用上面创建的指令,如下所示

<my-Directive></my-Directive>