Home > Article > Web Front-end > How to Set an iframe\'s 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>
<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>
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>
<code class="html"><iframe ng-src="{{currentProjectUrl}}"> <!-- Replace the text with actual content --> </iframe></code>
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!