在Angular js中从Go模板获取数据
I am new in Angular Js. I managed to receive the data from golang in angular js. But it's giving an output [object Object] when used in an alert box. I tried changing the delimiters of golang from {{ }} to <<< >>>, but the problem was not solved.
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"
}
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>
JS
var addBoxForAds = angular.module('addBoxForAds', []);
addBoxForAds.controller('AddBoxForAdsCtrl', function ($scope, $http){
var title = $http.get('<<<.vm.Title>>>'); //Data from GO; delimiters are changed.
alert(title);
});
What are the mistakes I made here? How can I get the data from golang in angularjs? How to use use the struct element UnUsedBoxes(which is an array of struct)?
$http.get
makes get request to server to fetch json data and you are just passing value straight to js-code. If I figured out you correctly, you need to change your code to
var title = '<<<.vm.Title>>>';
Or, you can make function in Go like in this dummy example (may look different on 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 work too:
// title := struct {title string} {"My Title"}
json_title, _ := json.Marshal(title)
w.Header().Set("Content-Type", "application/json")
w.Write(json_title)
}
And in js:
var title = $http.get('/title');