Modify content on a link using AngularJS

Currently, my setup looks like this:

HTML Code

<div ng-app="home" ng-controller="customersCtrl"> 
    <div ng-bind-html="home" id="content">{{content}}</div>
</div>

JS Code

angular.module('home', []).controller('customersCtrl', ['$scope', '$http', '$sce', function($scope, $http, $sce) {
    $http.get("http://www.example.de/home/").success(function (response) {
        document.getElementById("content").innerHTML = response;
    });
}]);

Everything is working fine, but now I want to change the content when a link is clicked, like this:

<a href="#home/">Home</a> | <a href="#user/">User</a>

Does anyone know how I can achieve this?

Answer №1

If you're looking to easily change text using a simple function call, my personal recommendation would be to use ng-click="" instead of <a href="#"></a>. Including # is typically used for route changes in AngularJS.

Based on your explanation, it seems like you're fetching some HTML codes from another website and suddenly Angular stops working. When using ng-bind-html, you'll need to 'sanitize' it as it is considered unsafe to bind HTML code directly.

Here is the code that should work for you:

HTML:

<div ng-app="myApp" ng-controller="customersCtrl" ng-init="content='test'"> 
    <div ng-bind-html="content | sanitize"></div>
    <a ng-click="changeContent('home')">Home</a> | <a ng-click="changeContent('user')">User</a>
</div>

Javascript:

angular.module('myApp', [])
    .filter('sanitize', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }])

    .controller('customersCtrl', ['$scope', '$http', '$sce', function($scope, $http, $sce) {
        $scope.changeContent = changeContent;

        function changeContent (content){
            if(content === 'home'){
                $http.get("http://www.example.de/home/").success(function (response) {
                    $scope.content = response;
                });            
            } else {
                // ......
            }
        }
    }]);

Edit: Updated spacing and corrected typos

Answer №2

To easily bind content, you can utilize double curly braces {{}} in Angular, also referred to as double binding

 <div ng-app="home" ng-controller="customersCtrl"> 
        <div ng-bind-html="home" id="content">{{content}}</div>
    </div>

<a ng-href="{{yourLink}}">Home</a>
Just to showcase 
<button ng-click="yourLink = 'foo'">change the link</button>

Similarly, Angular scope can be used here to update the view

angular.module('home', []).controller('customersCtrl', ['$scope', '$http', '$sce', function($scope, $http, $sce) {
        $http.get("http://www.example.de/home/").success(function (response) {
            $scope.content = response;
        });
    }]);

How does Angular update the view or content?

Angular utilizes watches to monitor all scopes. When a value is passed to the scope, Angular triggers the digest cycle to update the view or its content

To use single binding, simply add :: to the expression {{::yourLink}} This reduces Angular's watch overhead and improves performance

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

Restangular is throwing an error because it cannot find the reference for _

I encountered an issue with Restangular where I'm getting the error message: Uncaught ReferenceError: _ is not defined from restangular when trying to use it. Code Snippet: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angula ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

Learning the process of utilizing Json in Flot to create visually appealing graphs

I'm currently utilizing the Flot Graph Api to showcase bar charts and line charts on my client-side PHP environment. I am attempting to pass Json data to plot the graph as outlined in their examples. This is how I structure the Json data: [{"label": ...

Internet Explorer no longer supports SCRIPT tags in AJAX responses

We are currently facing an issue in our project where AJAX returns some code, and we utilize innerHTML to insert this code into a DIV. Subsequently, we scan this DIV for all script tags and execute the contents of these script tags using EVAL() (which add ...

Using Node JS to pass variables to the client

Currently, I am utilizing Node JS and Express for my server-side needs. In my server-side code, I pass a variable (sources) to my EJS template. Part of this variable is used to populate a list on the webpage. However, when a user clicks on an item in the ...

Issue with webpack failing to inject variables

I have encountered an issue while using the npm package got, which I am importing into one of my components. Strangely, when I run everything through Webpack, Safari is the only browser showing the error message: SyntaxError: Unexpected keyword 'cons ...

Is it feasible to utilize the Next.js (App Router) Context API to access this context in every fetch request?

To perform database queries, I require some context information. The context functions are not accessible on the client side, so I have been passing this context as args whenever I call a server component. However, I am exploring more efficient ways to h ...

Implementing the if/shim binding in Knockout.js

In my project, I am looking to develop a unique custom binding that functions similarly to the if binding. However, instead of completely removing the element from view, I want it to be replaced with another element of equal height whenever it needs to be ...

Error message: The Javascript Electron app is unable to find the node-fetch module when

Below is the code snippet from my gate.html file: <html> <head> <meta http-equiv='Content-Security-Policy' content='default-src 'self'; https://example.com.tr/validkeys.txt'> <meta http-equiv=&ap ...

Guide on installing React packages during runtime

My React project has a number of packages that need to be installed, but they take up a lot of disk space. I would like to install them only when necessary, after the user interacts with a specific component that requires these packages. Is there a way t ...

Disallow/bound the position of the marker on Google Maps

Is there a way to restrict the placement of markers on a map? I am looking for a solution that allows me to limit the marker position within a specific area, such as a town, with a radius of 10km. It should prevent users from dragging or creating new mark ...

Steps for building JSX with a loop

Recently diving into the world of React and Javascript, I've been attempting to assemble a JSX 'tree' dynamically using a loop rather than hard-coding the data. However, I find myself facing a hurdle where Visual Studio Code insists on havi ...

jQuery Toggle and Change Image Src Attribute Issue

After researching and modifying a show/hide jQuery code I discovered, everything is functioning correctly except for the HTML img attribute not being replaced when clicked on. The jQuery code I am using: <script> $(document).ready(function() { ...

Create an excel spreadsheet using HTML tables with the help of jQuery

Upon clicking a button, I aim to generate an excel sheet. Essentially, I am trying to achieve what is being discussed here (Kalle H. Väravas answer). If the following links are not working within Mozilla browser, then maybe my code requires ActiveXObject ...

Would parallax stars be overwhelming for a webpage?

I'm a newcomer to the world of web development and I have an idea to make stars move across my website. However, I'm concerned about whether this might be too much for a simple website to handle. Is there a way to optimize the code? const canvas ...

Choose various selections from a drop-down menu using AngularJs

I am currently working on a project where I need to be able to select multiple options from a dropdown menu. The code snippet for this functionality looks like the following: //Controller $scope.data = [{id: 1, Country: Zambia}, {id: 2, Coun ...

An error was encountered involving an unexpected token < at the beginning of a JSON file while using express with firebase

After setting up an authentication system in express using firebase auth, I established an endpoint in my express server: app.post('/users/login', (req, res) => { console.log('logging in...'); firebase.auth().signInWithEmail ...

Bluebird Enthusiastically Predicting the Outcome of a Complex Operation

Lately, I've been heavily utilizing Bluebird in my HAPI API development. However, I've encountered a perplexing issue that has left me puzzled due to either my understanding or lack of experience. Below is an example demonstrating the challenge ...

The middleware in Express.js is failing to execute the next function

I have been attempting to run a post function that contains a next(); within the code. To solve this issue, I have exported the function's definition from another file and am trying to call it through an express router. Unfortunately, the function is ...

Chrome on OSX Mavericks threw a RangeError because the maximum call stack size was exceeded

While attempting to run an Angular app using linemanjs in Chrome on a Mac, I encountered the following error: Uncaught RangeError: Maximum call stack size exceeded An interesting observation is that the site functions properly on Chrome on a Windows mach ...