绑定角度交叉的iframe,可能吗?

时间:2012-12-14 15:43:43

标签: angularjs

有没有什么方法可以将相同的范围/控制器/指令和内容绑定/共享到同一域中的另一个iframe中?

如果我可以在另一个iframe中拥有相同的ngApp,那么

会很酷。以前有人做过这样的事吗?

1 个答案:

答案 0 :(得分:11)

是的,这是可能的,你不需要做任何特别的事情,你只需要编译内容。

以下是一个示例: http://jsfiddle.net/gWgYM/

<强> HTML:

<div ng-app="app" ng-controller="test">
    <h1>The date is {{date}}</h1>
    <iframe frame=""></iframe>
</div>

<强>使用Javascript:

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

app.controller('test', function( $scope ) {
    $scope.date = new Date();
    window.setInterval(function() {
        $scope.date = new Date();
        $scope.$apply();
    }, 1000);
});

app.directive('frame', function( $compile ) {
    return function( $scope, $element ) {
        var $body = angular.element($element[0].contentDocument.body),
            template  = $compile('<p>The date in the iframe is {{date}}</p>')($scope);
        $body.append(template);
    };
});