Home > Article > Web Front-end > How to Set an iFrame\'s src Attribute from a Variable in AngularJS Using $sce Service?
To set the src attribute of an iframe from a variable in AngularJS, the $sce service must be injected into the controller.
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>
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!