首页  >  文章  >  web前端  >  如何在 AngularJS 中使用变量设置 iframe 的 src 属性?

如何在 AngularJS 中使用变量设置 iframe 的 src 属性?

Linda Hamilton
Linda Hamilton原创
2024-10-21 13:58:02502浏览

How to Set an iframe's src Attribute Using a Variable in AngularJS?

在 AngularJS 中使用变量设置 iframe src 属性

问题:

从变量设置 iframe 的 src 属性在 AngularJS 中不起作用,将属性留空。

代码摘录:

<code class="javascript">function AppCtrl($scope) {

    // ...

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

    }
}</code>
<code class="html"><div class="col-xs-12" ng-controller="AppCtrl">

    <ul class="">
        <li ng-repeat="project in projects">
            <a ng-click="setProject(project.id)" href="">{{project.url}}</a>
        </li>
    </ul>

    <iframe  ng-src="{{trustSrc(currentProject.url)}}">
        Something wrong...
    </iframe>
</div></code>

解决方案:

问题在于控制器中缺少 trustSrc 函数的定义。要使用变量设置 src 属性,您需要使用 AngularJS 的 $sce 服务来信任 URL:

<code class="javascript">function AppCtrl($scope, $sce) {

    // ...

    $scope.setProject = function (id) {
        $scope.currentProject = $scope.projects[id];
        $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
        console.log( $scope.currentProject );
    }
}</code>
<code class="html"><iframe  ng-src="{{currentProjectUrl}}">
    <!-- Replace the text with actual content -->
</iframe></code>

通过注入 $sce 服务并使用 trustAsResourceUrl,您可以确保 URL 是被视为可信,可以设置为 iframe 的 src 属性。

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

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