热门搜索 :
考研考公
您的当前位置:首页正文

angularjs 手动编译代码

来源:东饰资讯网

有些时候我们会遇到 html不是预先在DOM中定义的情况,比如从后台传递过来的html.
angular出于安全考虑,我们插入的html代码里的事件和绑定的ng-model都不会起作用
这些html 如果含有angularjs的 指令 则需要手动编译下.

使用$compile

  1. 基本
    <pre>
    //获得模版
    var template = $compile("<div ng-click='testFun();'>{{test}}</div>");
    //数据填充至模版生成 视图
    var newDom = template($scope);
    //填充到指定位置
    $("#test").html(newDom);
    </pre>

  2. 连写
    <pre>
    //连这写
    var newDom = $compile("<div>{{test}}</div>")($scope);
    $("#test").html(newDom);
    </pre>

使用封装的指令

  1. 指令
    <pre>
    (function() {
    'use strict';
    var module = angular.module('angular-bind-html-compile', []);
    module.directive('bindHtmlCompile', ['$compile',
    function($compile) {
    return {
    restrict: 'A',
    link: function(scope, element, attrs) {
    scope.$watch(function() {
    return scope.$eval(attrs.bindHtmlCompile);
    },
    function(value) {
    element.html(value);
    $compile(element.contents())(scope);
    });
    }
    };
    }]);
    } ());
    </pre>

  2. html/js
    <pre>
    <code>
    $scope.htmlDom = "<div ng-click='testFun();'>{{test}}</div>";
    <code>
    </pre>
    <pre>
    <div bind-html-compile="htmlDom" ></div>
    </pre>
    需要在app.js 中指定依赖angular-bind-html-compile模块. 使用封装指令确实事半功倍.

$interpolate 待写

Top