为什么当我尝试为iframe-src属性构建URL时,AngularJS会抛出错误

Why does AngularJS throw an error when I try to build a URL for an iframe src attribute?

本文关键字:AngularJS 错误 出错 URL 构建 属性 iframe-src 为什么      更新时间:2023-09-26

我一直在修改AngularJS指令,我不明白为什么我试图用表达式构建iframe-src属性会引发错误。抛出的错误引用了以下URL,但恐怕我觉得它不是很有启发性:

http://errors.angularjs.org/1.3.14/$interpole/nooncat?p0=https%3A%2F%2Fwww.youtube.com%2Fembed%2F%7B%7BvideoId%7%7D

这到底意味着什么?我该怎么办?

以下是相关的JavaScript和HTML:

angular.module("myModule", [])
	.directive("myDirective", function() {
		return {
			restrict: "EA",
			scope: {
				videoId: "@videoId",
				width: "@width",
				height: "@height"
			},
			// This seems to work as expected.
			//template: '<iframe width="432" height="243" src="https://www.youtube.com/embed/8aGhZQkoFbQ" frameborder="0" allowfullscreen></iframe>',
			// This seems to work as expected except for adding a little extra whitespace after the values.
			//template: '<iframe width="{{width}}" height="{{height}}" src="https://www.youtube.com/embed/8aGhZQkoFbQ" frameborder="0" allowfullscreen></iframe>',
			// This throws an error that refers to http://errors.angularjs.org/1.3.14/$interpolate/noconcat?p0=https%3A%2F%2Fwww.youtube.com%2Fembed%2F%7B%7BvideoId%7D%7D.
			template: '<iframe width="432" height="243" src="https://www.youtube.com/embed/{{videoId}}" frameborder="0" allowfullscreen></iframe>',
			replace: true
		};
	});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<my-directive video-id="8aGhZQkoFbQ" width="432" height="243"></my-directive>

我感谢你的启迪。

我将保留以上内容以供参考,但这是一个使用控制器和$sce.trustAsResourceUrl的编辑版本,正如Muhammad Reda的回答中所建议的那样,以防它可以帮助任何人一起查看:

angular.module("myModule", ["ngSanitize"])
	.directive("myDirective", function() {
		return {
			restrict: "EA",
			scope: {
				videoId: "@videoId",
				width: "@width",
				height: "@height"
			},
			template: '<iframe width="432" height="243" src="{{srcUrl}}" frameborder="0" allowfullscreen></iframe>',
			replace: true,
			controller: function($scope, $sce) {
				$scope.srcUrl = $sce.trustAsResourceUrl("https://www.youtube.com/embed/" + $scope.videoId);
			}
		};
	});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-sanitize.min.js"></script>
<my-directive video-id="8aGhZQkoFbQ" width="432" height="243"></my-directive>

您的url需要包装在$sce.trustAsResourceUrl(YOUR_URL) 周围

文件。

在指令中添加controller

angular.module("myModule", ['ngSanitize'])
    .directive("myDirective", function() {
        .....
        controller: function($scope, $sce) {
            $scope.iframeUrl = 'https://www.youtube.com/embed/' + $scope.videoId;
            $scope.iframeUrl = $sce.trustAsResourceUrl($scope.iframeUrl);
        },
        template: '<iframe src="{{ iframeUrl }}" frameborder="0" allowfullscreen></iframe>'
    })