Home  >  Article  >  Web Front-end  >  How to Set an iFrame\'s src Attribute from a Variable in AngularJS Using $sce Service?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 13:56:30765browse

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>

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>

Template Modification

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

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

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!

Statement:
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