我是Angular Js的新手。我设法从角度js的golang接收数据。但是当它在警告框中使用时,它会输出 [object Object] 。我尝试将golang的分隔符从 {{}} 更改为<<< >>> ,但问题没有解决。
Go code :(我正在使用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"
}
结构 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);
});
我在这里犯了什么错误?如何从angularjs中获取golang中的数据?如何使用struct元素 UnUsedBoxes (这是一个struct数组)?
答案 0 :(得分:2)
$http.get
向服务器发出获取请求以获取json数据,并且您只是将值直接传递给js-code。如果我没弄错,你需要将代码更改为
var title = '<<<.vm.Title>>>';
或者,您可以像在这个虚拟示例中那样在Go中创建函数(在beego框架上可能看起来不同):
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)
}
在js:
var title = $http.get('/title');