Home >Web Front-end >JS Tutorial >How to Trust and Set iFrame Src Attribute from a Variable in AngularJS?
Setting iFrame Src Attribute from a Variable in AngularJS
In AngularJS, you may encounter challenges when attempting to set the src attribute of an iFrame from a variable. To address this issue, we must delve into the provided code:
<br>function AppCtrl($scope) {</p> <pre class="brush:php;toolbar:false">$scope.projects = { 1 : { "id" : 1, "name" : "Mela Sarkar", "url" : "http://blabla.com", "description" : "A professional portfolio site for McGill University professor Mela Sarkar." }, 2 : { "id" : 2, "name" : "Good Watching", "url" : "http://goodwatching.com", "description" : "Weekend experiment to help my mom decide what to watch." } }; $scope.setProject = function (id) { $scope.currentProject = $scope.projects[id]; console.log( $scope.currentProject ); }
}
The crux of the issue lies in the absence of the trustSrc function referenced in the ng-src attribute. You need to inject the $sce service into the controller to utilize the trustAsResourceUrl method for sanitizing the URL string.
<br>function AppCtrl($scope, $sce) { // Injected $sce service</p> <pre class="brush:php;toolbar:false">// ... $scope.setProject = function (id) { $scope.currentProject = $scope.projects[id]; $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url); console.log( $scope.currentProject ); console.log( $scope.currentProjectUrl ); }
}
Within the template:
<br><iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe><br>
By employing trustAsResourceUrl, you can safely set the URL within the src attribute.
The above is the detailed content of How to Trust and Set iFrame Src Attribute from a Variable in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!