Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-21 13:58:02
Original
592 people have browsed it

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

Setting an iframe src Attribute Using a Variable in AngularJS

Problem:

Setting an iframe's src attribute from a variable in AngularJS is not working, leaving the attribute blank.

Excerpt from Code:

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

    // ...

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

    }
}</code>
Copy after login
<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>
Copy after login

Solution:

The issue lies in the missing definition of the trustSrc function in the controller. To set the src attribute using a variable, you need to use AngularJS's $sce service to trust the 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>
Copy after login
<code class="html"><iframe  ng-src="{{currentProjectUrl}}">
    <!-- Replace the text with actual content -->
</iframe></code>
Copy after login

By injecting the $sce service and using trustAsResourceUrl, you ensure that the URL is treated as trustworthy and can be set as the src attribute of the iframe.

The above is the detailed content of How to Set an iframe\'s src Attribute Using a Variable in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template