首页  >  文章  >  web前端  >  如何在 AngularJS 中信任并设置变量的 iFrame Src 属性?

如何在 AngularJS 中信任并设置变量的 iFrame Src 属性?

Patricia Arquette
Patricia Arquette原创
2024-10-21 13:57:02899浏览

How to Trust and Set iFrame Src Attribute from a Variable in AngularJS?

在 AngularJS 中从变量设置 iFrame Src 属性

在 AngularJS 中,尝试设置 iFrame 的 src 属性时可能会遇到挑战来自一个变量。为了解决这个问题,我们必须深入研究提供的代码:

<br>function AppCtrl($scope) {<pre class="brush:php;toolbar:false">$scope.projects = {

    1 : {
        "id" : 1,
        "name" : "Mela Sarkar",
        "url" : "http://blabla.com",
        "description" : "A professional portfolio site for McGill University professor Mela Sarkar."
    },

    2 : {
        "id" : 2,
        "name" : "Good Watching",
        "url" : "http://goodwatching.com",
        "description" : "Weekend experiment to help my mom decide what to watch."    
    }
};

$scope.setProject = function (id) {
    $scope.currentProject = $scope.projects[id];
    console.log( $scope.currentProject );

}

}

问题的症结在于 ng-src 属性中缺少引用的 trustSrc 函数。您需要将 $sce 服务注入到控制器中,以利用 trustAsResourceUrl 方法来清理 URL 字符串。

<br>function AppCtrl($scope, $sce) { // 注入 $sce service</p><pre class="brush:php;toolbar:false">// ...

$scope.setProject = function (id) {
  $scope.currentProject = $scope.projects[id];
  $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
  console.log( $scope.currentProject );
  console.log( $scope.currentProjectUrl );

}

}

模板内:

<br><iframe ng-src=" {{currentProjectUrl}}"> <!--内容--> </iframe><br>

通过使用 trustAsResourceUrl,您可以安全地在 src 属性中设置 URL。

以上是如何在 AngularJS 中信任并设置变量的 iFrame Src 属性?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn