Extracting information from a Go template within an AngularJS environment

I am brand new to Angular Js. I successfully retrieved data from golang in angular js. However, when I use it in an alert box, it displays as [object Object]. I attempted to fix this issue by changing the delimiters of golang from {{ }} to <<< >>>, but unfortunately, the problem persisted.

Here is my Go code (I am using beego):

func (receiver *AdsController) LoadNewCampaignPage()  {
    view := viewmodels.NewCampaignPageViewModel{}
    view.Title = "New Campaign"
    receiver.Data["vm"] = view
    receiver.Layout = "layouts/ads_header.html"
    receiver.TplName = "templates/ads_add_campaign.html"
}

The struct viewmodels.NewCampaignPageViewModel{}:

type NewCampaignPageViewModel struct {
    Title           string
    ProfileName     string
    ProfilePicture  string
    UnUsedBoxes     []models.Box
    ErrorMessage    string
}

HTML:

<div ng-controller="AddBoxForAdsCtrl">
    <button class="_button _button-3" ng-click="showHiddenForm()">Add Box</button>
</div>

JavaScript:

var addBoxForAds = angular.module('addBoxForAds', []);
addBoxForAds.controller('AddBoxForAdsCtrl', function ($scope, $http){
     var title = $http.get('<<<.vm.Title>>>'); //Data from GO; delimiters have been changed.
     alert(title);
});

What mistakes have I made here? How can I effectively retrieve data from golang in angularjs? And how do I utilize the struct element UnUsedBoxes (which is an array of structs)?

Answer №1

$http.get is used to send a get request to the server in order to retrieve JSON data, and you are simply passing the value directly to the JavaScript code. If I understand correctly, you will need to update your code like this:

var title = '<<<.vm.Title>>>';

Alternatively, you could create a function in Go similar to this example (which may vary on the Beego framework):

import (
    "net/http"
    "encoding/json"
)

func main() {
    http.HandleFunc("/title", title_handler)
    http.ListenAndServe(":8000", nil)
}

func title_handler(w http.ResponseWriter, r *http.Request) {
    title := map[string]string{"title": "My Title"}
    // This should also work:
    // title := struct {title string} {"My Title"}

    json_title, _ := json.Marshal(title)
    w.Header().Set("Content-Type", "application/json")
    w.Write(json_title)
}

In your JavaScript code:

var title = $http.get('/title');

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

Numerous scripts available for achieving a responsive layout using (window).resize event

I am currently in the process of creating a one-page website with a responsive design. On smaller screens, I have implemented an animated scroll plugin to navigate between content divs, while on larger screens, I am using a plugin to toggle the visibility ...

Separate and add on the change validity status of an AngularJS form

If you want to test it out, check this jsFiddle link: HERE (it's recommended to view on a new jsFiddle, refer to the EDIT section of this post) I've noticed what seems like a bug in AngularJS or at least an unexpected behavior. When I detach a f ...

Utilizing React's useState with array.map for handling multiple elements

I want to create multiple useStates for dynamically generated elements within an array.map. Each element in the array.map should share the same useState but have a unique assigned value. For instance, if the array.map contains three different elements, e ...

Creating a spacious text box for an enhanced Ajax search feature

I'm currently working on an AJAX application that allows users to input the name of a movie, and then loads results from the database through jquery using a PHP API. However, I'm facing a challenge in implementing a text box with the following re ...

What are some strategies for bypassing the restrictions on Cross Origin Requests?

I am currently facing an issue with retrieving a file from the server where my PHP code is hosted, which is a web hosting service. This problem is not unfamiliar to me as I have previously encountered difficulties accessing files from HTML, whether locall ...

The shopping cart in our e-commerce website is refreshed in real-time thanks to the integration of J

I am currently enhancing the Codeigniter Cart with JQuery by making an Ajax call for updates. Below is my JQuery function: $(function() { $('.cart_form select').on('change', function(ev) { var rowid = $(this).attr('c ...

Trouble activating header checkbox on initial click

Hello everyone, I have a question about two views: 1- Index 2- Edit In my grid, the header has a single checkbox. When I try to click the checkbox to select all rows, it doesn't work properly. The first time I click to uncheck and then check it agai ...

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

Using AngularJs ngBind may cause syntax highlighted code snippets to not display properly

For my web application, I utilized a Syntax highlighting API to highlight code snippets. To achieve this, I integrated highlightjs. Within a popup modal, I included the <pre> tag and expected it to display my highlighted xml string when opened. HTML ...

JavaScript function implemented to add query parameters to HTTP requests

While reviewing my Google Analytics data, I noticed some recurring requests with a script in the query parameter. The format looks something like this: /about?RaNDMPRMz='-function(){debugger}()-">\"><scrIpt>debugger</scrIpt>< ...

I am looking to modify the JSON format of the API response

Received this response from the API and need to convert the JSON format below: Original: "data": [ [ { "isFile": "true", "fileType": "image", "filesize": 100793, ...

What are the potential issues with my validation function specifically designed for the select element?

After 3 years of working with JavaScript, I found myself unable to use simple validator libraries. So, I made the decision to create my own. This validator works by adding the attribute jmust to all inputs, select elements, textareas, etc. (I haven't ...

How can I pass arguments from a Python command line program (compiled to an EXE) to a JavaScript file?

As I work on developing a node program, I've come across certain abilities that Python possesses which JavaScript lacks, such as utilizing Python-specific modules. To bridge this gap, I made the decision to compile Python files into EXE and then invok ...

Nuxt middleware failing to verify user's logged-in status

I am currently working on implementing user authentication and redirection logic based on the user's authentication status. For instance, if a logged-in user tries to access the login or signup page, they should be automatically redirected. To achieve ...

ReactJs throws an error of "Uncaught SyntaxError: Unexpected token '<' while utilizing the map() function in ReactJs that produces JSX (specifically MaterialUi-icons) within an array

In the file constant.js, I have defined object names and icons as keys. The key icon contains the icon component from @mui/icons-material, but when I attempt to retrieve the value from the icon, I encounter an error. Uncaught SyntaxError: Unexpected toke ...

Getting the user's name and country using `auth().createUserWithEmailAndPassword` is a simple process

Hey there fellow developers. I'm fairly new to react native and I'm trying to implement firebase authentication for a project. However, I'm stuck on how to include user name and country when using the standard auth().createUserWithEmailAndPa ...

Issue with React.useEffect not functioning in Express application

I'm having trouble with the state not updating or re-rendering in my code. I've tried logging from inside the useEffect function but nothing seems to happen. Any suggestions on how to make the useEffect work properly? app.js var createError = re ...

Master the art of positioning in three.js framework

I am a beginner in javascript and three.js, and I am currently exploring how to determine the 3d positions on a webpage. For instance, I want to place a point light at the coordinates (50,20,10) in x, y, z values. How can I determine where these x, y, z va ...

The most effective method for transferring asynchronous data to pages in Next.js

My current directory structure: - components - NavBar - Header - Layout - pages - pages - demo.js - _app.js - index.js // index.js import React from 'react'; import NewLayout from "../../components/NewLayout/NewLayou ...

Ways to automatically check a checkbox using jQuery

Is there a way to use jQuery to programmatically click a checkbox? I am trying to create a hidden checkbox that will be checked when a user clicks on a specific element, but my current code is not functioning as expected and I am unsure why. You can view ...