Setting iframe src Attribute from Variable in AngularJS
In AngularJS, you may encounter issues when attempting to set the src attribute of an iframe from a variable. To address this, here's a step-by-step guide:
1. Inject the $sce Service
Inject the $sce (Strict Contextual Escaping) service into your controller to handle sanitization.
<code class="js">function AppCtrl($scope, $sce) { // ... }</code>
2. Trust the Resource URL
Use $sce.trustAsResourceUrl within the controller to ensure the URL is safe.
<code class="js">$scope.setProject = function (id) { $scope.currentProject = $scope.projects[id]; $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url); }</code>
3. Update the Template
In the template, bind the ng-src attribute to the trusted URL variable.
<code class="html"><iframe ng-src="{{currentProjectUrl}}"> <!-- content --> </iframe></code>
Example Code
<code class="js">function AppCtrl($scope, $sce) { $scope.projects = { // ... }; $scope.setProject = function (id) { $scope.currentProject = $scope.projects[id]; $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url); }; }</code>
<code class="html"><ul ng-repeat="project in projects"> <li ng-click="setProject(project.id)">{{project.name}}</li> </ul> <iframe ng-src="{{currentProjectUrl}}"> Something wrong... </iframe></code>
Additional Notes
The above is the detailed content of How to Set iframe src Attribute from a Variable Safely in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!