angularjs - 如何将 Controller 绑定(bind)到动态添加的 HTML?

标签 angularjs angularjs-scope

我从 Controller 注入(inject) html 输入,我正在尝试绑定(bind)范围变量,但它不起作用。
这是我的代码
HTML :

    <div ng-controller='addHTML'>
       <div ng-bind-html="trustedHtml"></div>
       <code>{{user}}</code>
    </div>

CSS :
var app = angular.module('app',[]);
var addHTML = function ($scope,$sce) {
     $scope.user = {};
     $scope.user.someVariable = "";

    //inject some html
    $scope.html = '<input type="text" ng-model="user.someVariable">';
    $scope.trustedHtml = $sce.trustAsHtml($scope.html);

};

你可以在这里找到它:http://jsbin.com/miluguni/1/watch?html,js,output

输入输入时,范围变量不会更改。

最佳答案

ngBindHtml指令不会 $compile 模板,它只会将模板插入 DOM。

我复制了ngBindHtml ( source code ) 并添加了 $compile

新指令:

app.directive('compileHtml',['$sce', '$parse', '$compile', 
  function($sce, $parse, $compile){
  return {
    link: function(scope,element,attr){
      var parsed = $parse(attr.compileHtml);
      function getStringValue() { return (parsed(scope) || '').toString(); }            
      scope.$watch(getStringValue, function (value) {
        var el = $compile($sce.getTrustedHtml(parsed(scope)) || '')(scope);
        element.empty();
        element.append(el);        
      });       
    } 
  };
}]);

模板:
<div compile-html="trustedHtml"></div>

这是一个演示:http://jsbin.com/miluguni/3/edit

关于angularjs - 如何将 Controller 绑定(bind)到动态添加的 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21914760/

相关文章:

javascript - 配置angularjs模块发送补丁请求

javascript - Controller 作为带有 ng-click 的 vm

javascript - AngularJS - 无法在 View 中访问检索到的 JSON 数据

javascript - 在javascript中获取传递键值的值

AngularJS 和 Angular 翻译 : Using the translate filter in an object literal

javascript - 更新图像网址时,图像不会在前端呈现

angularjs - Angular 不从模型中选择单选按钮

javascript - getRowHeight() 不适用于 rowModelType = 'infinite' 和最新的 ag-grid 版本

javascript - 在 Angular 中基于前一个元素使用 ng-hide

javascript - 使用字符串与属性名称进行 Angular 绑定(bind)