我一直在修补AngularJS指令,但我不明白为什么我尝试使用表达式构建iframe src属性的尝试会触发错误。引发的错误引用了以下URL,但恐怕并没有启发性:
http://errors.angularjs.org/1.3.14/ $ interpolate / noconcat?p0 = https%3A%2F%2Fwww.youtube.com%2Fembed%2F%7B%7BvideoId%7D%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>
您的网址需要换行 $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>'
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句