AngularJS 指令模板和可信资源的摘要周期限制

AngularJS digest cycle limit with directive template and trusted resource

似乎指令正在替换模板,然后 运行 更新源的信任资源函数,然后再次更新模板并陷入循环。但这是推荐的方法?? html:

<player videos='[{"type":"mp4","src":"http://vjs.zencdn.net/v/oceans.mp4","poster":"http://www.videojs.com/img/poster.jpg","captions":"http://www.videojs.com/vtt/captions.vtt"},{"type":"webm","src":"http://vjs.zencdn.net/v/oceans.webm"}]' />

这是 javascript:

module.directive('player', ['$sce', function ($sce) {
    'use strict';
    return {
        restrict: 'E',
        scope: {
            videos: '='
        },
        link: function (scope, element, attrs) {
            scope.trustSrc = function(src) {
                return $sce.trustAsResourceUrl(src);
            }
        },
        template: '<video preload="none" poster="{{ trustSrc(videos[0].poster) }}">' +
            '<source ng-repeat="item in videos" ng-src="{{ trustSrc(item.src) }}" type="video/{{ item.type }}" />' +
            '<track kind="captions" ng-src="{{ trustSrc(videos[0].captions) }}" srclang="en" label="English" />' +
            '</video>'
    };
}]);

这是一个有效的 fiddle:

http://jsfiddle.net/kmturley/mgosw7kx/4/

您在 videos 属性中的字符串和 $scope 变量之间通过作用域使用双向绑定:{ videos: '=' } 不应该这样使用。

根据文档:

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name.

您可以:

scope: {},
link: function(scope, element, attr) {
   scope.videos = attr['videos'];
}

或使用“&”,它将return一个函数在父作用域的上下文中执行:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name.

在这种情况下,您必须这样做:

scope: {videos: '&'},
link: function(scope, element, attr) {
   scope.videos = scope.videos();
}

有关隔离作用域的更多信息:$compile