Utilizing Angular.js to Bind AJAX Content to Web Pages

I recently experimented with coding using angular.js version 1.5.

<div class="container clearfix" id="mainMenu" ng-controller="MainMenuController as mainMenu">
    <ul class="menu clearfix" ng-init="tab = 'ant'">
        <li class="menu1" ng-class="{menu_active:mainMenu.isSelected('ant')}">
            <a href="#!/antTalkList" ng-click="mainMenu.selectTab('ant')">Ant Talk</a></li>
        <li class="menu2" ng-class="{menu_active:mainMenu.isSelected('expert')}">
            <a href="#!/expertTalkList" ng-click="mainMenu.selectTab('expert')">Expert Talk</a></li>
        <li class="menu3" ng-class="{menu_active:mainMenu.isSelected('club')}">
            <a href="#!/clubTalkList" ng-click="mainMenu.selectTab('club')">Club Talk</a></li>
        <li class="menu4" ng-class="{menu_active:mainMenu.isSelected('finance')}">
            <a href="#!/finance" ng-click="mainMenu.selectTab('finance')">Finance Talk</a></li>
        <li class="menu5" ng-class="{menu_active:mainMenu.isSelected('shopping')}">
            <a href="#!/shopping" ng-click="mainMenu.selectTab('shopping')">Shopping Talk</a></li>
        <li class="menu6" ng-class="{menu_active:mainMenu.isSelected('more')}">
            <a href="#!/settings" ng-click="mainMenu.selectTab('more')">More</a></li>
    </ul>
    <div class="combine_content" id="content-area" ng-bind-html="content">
    </div>
</div>

As you can see, I have used ng-bind-html="content" which will display the selected menu item's content.

To achieve this functionality, I coded my app.js like this: Each menu's HTML code is fetched and stored in tabViews[tabName] through an HTTP AJAX call. When a menu is selected, the content of that menu is stored in mainMenu.content as tabViews[tabName].

(function(){
    var app = angular.module('stocktalkApp', []);
    app.controller('MainMenuController', function($scope, $http){

    this.tabViews = [];
    this.tab='ant';

     $http({
            method : "GET",
            url : "ant/view"
        }).then(function mySucces(response) {
            $scope.mainMenu.tabViews['ant'] = response;
            $scope.content = $scope.mainMenu.tabViews[$scope.mainMenu.tab];
        }, function myError(response) {
        });
     $http({
            method : "GET",
            url : "expert/view"
        }).then(function mySucces(response) {
            $scope.mainMenu.tabViews['expert'] = response;
        }, function myError(response) {
        });  

    this.selectTab =  function(tabName){
        this.tab = tabName;
        this.content = this.tabViews[this.tab];
    };
    this.isSelected = function(tabName){
        return tabName === this.tab;
    }
});
})();

However, I encountered an error message:

angular.js:13920 Error: [$sce:unsafe] http://errors.angularjs.org/1.5.8/$sce/unsafe
.

My question now is, how can I display the page content in HTML?

Update:

I made adjustments to my code by replacing response with response.data in the AJAX calls, but the same error persists.

Here is the updated HTML code:

<div class="combine_content" id="content-area" ng-bind-html="makeTrusted(content)"></div>

And this is my revised app.js code:

$scope.makeTrusted = function(htmlCode) {
    return $sce.trustAsResourceUrl(htmlCode);
}

 $http({
        method : "GET",
        url : "ant/view"
    }).then(function mySucces(response) {
        $scope.mainMenu.tabViews['ant'] = response.data;
        $scope.content = $scope.mainMenu.tabViews[$scope.mainMenu.tab];
    }, function myError(response) {
    });
 $http({
        method : "GET",
        url : "expert/view"
    }).then(function mySucces(response) {
        $scope.mainMenu.tabViews['expert'] = response.data;
    }, function myError(response) {
    });

Answer №1

To ensure security, it is important to inject the $sce service into the controller and use the trustAsResourceUrl method on the URL.

Controller

App.controller('AppController', ['$http', '$scope', '$sce',
    function($http, $scope, $sce) {
     $scope.makeTrusted= function(html_code) {
        return $sce.trustAsResourceUrl(html_code);
    }
}

HTML

 <div class="combine_content" id="content-area" ng-bind-html="makeTrusted(content)">
  </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a JavaScript IIFE library into a React Component

Hello, I am currently in the process of learning React JS and there are two JavaScript files that I am working on: Polyfill.js -> hosted on github CustomNavbar.js -> created by me Here is the structure of polyfill.js: export default (function(win ...

When a ng-model is added, the input value disappears

i am currently working on a form that contains angular values. <tr ng-repeat="alldata in c.da"> <td>{{alldata.id}}</td> <td><input type="text" class="form-control" value="{{alldata.name}}" ...

Tips for adjusting the size of an imported item in Three.js?

Currently, I am utilizing Three.js for my project and I am importing .OBJ file using OBJ LOADER () Everything has been working smoothly thus far, but I have come across an issue that has me stumped. I am trying to figure out how to change the width and he ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

Rendering a dynamic list of asynchronous components in Vue 3, with support for extension

Could you please assist me in resolving this issue? I've spent countless hours searching for a solution, but I can't seem to make it work. Vue is still very new to me. Let me provide some more context. I have an asynchronous component that i ...

Hiding the right CSS border for every even number in AngularJS using a loop

I am currently in the process of building an application using AngularJS and the Ionic framework. My goal is to display a right border only for odd numbers. Below is the snippet of my code: <div class="media-body" style="padding-bottom:25px;"> ...

The dropdownlists mysteriously vanish forever after a modal popup, likely due to a timer issue

We are encountering some unexpected behavior with dropdown lists on a relatively complex webpage when using IE6. The layout of the page consists of 2 update panels, each containing a GridView that displays data in a master-details format. Additionally, eac ...

Using Angular's $filter to target a specific field

I'm attempting to use the $filter function in my controller, within a $watch function, to filter specific fields. I am having trouble understanding the documentation provided. The situation: I have a dropdown menu that serves as the filter parameter. ...

The use of callback functions with Model.findOne() in Mongoose is now deprecated, and will result

Think about this: app.get("/posts/:postId", function(req, res) { const requestedPostId = req.params.postId; Post.findOne({_id: requestedPostId}, function(err, post) { res.render("post", { title: post.title, content ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

Get the page downloaded before displaying or animating the content

Is there a method to make a browser pause and wait for all the content of a page to finish downloading before displaying anything? My webpage has several CSS3 animations, but when it is first loaded, the animations appear choppy and distorted because the ...

React JS FormControl not functioning properly to toggle checkbox within a modal window

Upon editing a specific resource, a modal pops up to record the changes and update the application. Extracted from the homepage rfc const [flags,setFlags] = React.useState({}) . . . flags[object1]={flag1: true, flag2:false}; flags[object2]={flag1: true, f ...

Is there a more optimal way to choose lines than the Bresenham algorithm?

In my HTML canvas project, I am currently drawing lines using a 2d-array that represents blocks of 10x10 pixels. I use Bresenham's algorithm to store line-ids in this array so that I can determine which line is selected. While this method works, I fi ...

Managing Asynchronous Operations in Node.js

Hi everyone, I've hit a roadblock while trying to resolve an asynchronous problem in my Node.js code let isComplete = false; setTimeOut(() => { isComplete = true }, 1000) let count = 0; while(!isComplete) { console.log(count++) } I find that al ...

`Check out Vue3's property watching feature`

Currently, I have a form that is being edited and the created method is used to prefill the form information from an api call, which works perfectly fine. However, my goal is to monitor the fields in the form. If any of them are edited, I want to set a va ...

What is causing the TypeError in Discord.js when trying to read the 'voice' property? Any help troubleshooting this issue would be greatly appreciated

Hey everyone, I'm having an issue with my play.js file that I obtained from a Source Bin. If anyone could provide some assistance, it would be greatly appreciated. const ytdl = require("ytdl-core"); const ytSearch = require("yt-search"); //Global que ...

Enhancing Javascript Dialog Box with a Touch of Animation

Collaborating with the incredibly talented Mark Eirich has been an amazing experience. We have been working on revamping a JavaScript dialog box together, and Mark has set up something on JSFiddle that will be incredibly beneficial. However, I am seeking a ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...