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.
function AppCtrl($scope, $sce) {
// ...
}
2. Trust the Resource URL
Use $sce.trustAsResourceUrl within the controller to ensure the URL is safe.
$scope.setProject = function (id) {
$scope.currentProject = $scope.projects[id];
$scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
}
3. Update the Template
In the template, bind the ng-src attribute to the trusted URL variable.
Example Code
function AppCtrl($scope, $sce) {
$scope.projects = {
// ...
};
$scope.setProject = function (id) {
$scope.currentProject = $scope.projects[id];
$scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
};
}
- {{project.name}}
Additional Notes
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3