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

How to Set an iFrame\'s src Attribute from a Variable in AngularJS Using $sce Service?

Barbara Streisand
Release: 2024-10-21 13:56:30
Original
757 people have browsed it

How to Set an iFrame's src Attribute from a Variable in AngularJS Using $sce Service?

Setting iFrame src Attribute from Variable in AngularJS

To set the src attribute of an iframe from a variable in AngularJS, the $sce service must be injected into the controller.

Controller Modification

In the AppCtrl, inject the $sce dependency:

<code class="js">function AppCtrl ($scope, $sce) {
    // ...
}</code>
Copy after login

Then, inside the setProject function, trust the URL using trustAsResourceUrl:

<code class="js">$scope.setProject = function (id) {
    $scope.currentProject = $scope.projects[id];
    $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
}</code>
Copy after login

Template Modification

In the template, use the currentProjectUrl variable in the ng-src attribute:

<code class="html"><iframe ng-src="{{currentProjectUrl}}"></iframe></code>
Copy after login

This approach ensures that the URL is handled securely by AngularJS and prevents potential cross-site scripting vulnerabilities.

The above is the detailed content of How to Set an iFrame\'s src Attribute from a Variable in AngularJS Using $sce Service?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!