动态地将Angularjs绑定到新创建的html元素

Ty *_*son 18 model-binding angularjs

我有一个带有多个标签的标签页,一旦点击就会调用服务来返回一些数据.其中一些数据返回html表单并且非常随机.我想收集输入的值,并通过服务将数据发送回服务器.我遇到的问题是我无法从动态创建的html中的输入元素中获取数据.

我创建了一个Plunker来展示问题所在.请注意,html值可以随时更改,因此硬编码html将无法正常工作.这里是来自plunker的代码,但请查看plunker以获得最佳视图.

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $sce, $compile) {
    $scope.name = 'World';
    $scope.html = "";

    $scope.htmlElement = function(){
        var html = "<input type='text' ng-model='html'></input>";
        return $sce.trustAsHtml(html);
    }

});
Run Code Online (Sandbox Code Playgroud)

的index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <div ng-bind-html="htmlElement()"></div>

    {{html}}

  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

Sar*_*rah 26

一种解决方案是使用带有$ templateCache的ngInclude,如此Plunker中所示.

有几点需要注意.

第一个是,你可以使用服务获取您的模板,并将其添加到$ templateCache,描述在这里(例如复制):

myApp.service('myTemplateService', ['$http', '$templateCache', function ($http, $templateCache) {
  $http(/* ... */).then(function (result) {
    $templateCache.put('my-dynamic-template', result);
  });
}]);
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其包含在模板中,如下所示:

<div ng-include="'my-dynamic-template'"></div>
Run Code Online (Sandbox Code Playgroud)

ngInclude将允许对html字符串进行数据绑定,因此您不需要ngBindHtml.

第二个是,当ngInclude创建一个新范围时,访问html新创建范围之外的属性将无法正常工作,除非您通过父范围内的对象访问它(例如,ng-model="data.html"而不是ng-model="html".请注意,$scope.data = {}父范围中的对象是是什么使得html在这种情况下可以在ngInclude范围之外访问.

(有关为什么应始终在ngModel中使用点的原因,请参阅此答案.)


编辑

正如您所指出的,使用服务返回HTML时,ngInclude选项的用处不大.

这是编辑的plunker,它带有一个使用$ compile的基于指令的解决方案,如上面David的评论.

相关补充:

app.directive('customHtml', function($compile, $http){
  return {
    link: function(scope, element, attrs) {
      $http.get('template.html').then(function (result) {
        element.replaceWith($compile(result.data)(scope));
      });
    }
  }
})
Run Code Online (Sandbox Code Playgroud)


vic*_*chi 6

根据Sarah的回答,我创建了一个结构来放置指令

.directive('dynamic', function(AmazonService, $compile) {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      AmazonService.getHTML()
     .then(function(result){
       element.replaceWith($compile(result.data)(scope));
     })
     .catch(function(error){
       console.log(error);
     });
   }
 };
});
Run Code Online (Sandbox Code Playgroud)

并在HTML中:

<dynamic></dynamic>
Run Code Online (Sandbox Code Playgroud)

谢谢莎拉,帮了很多!!!