1

我是 Angular Js 的新手。我设法从 Angular js 中接收来自 golang 的数据。但是在警报框中使用时会给出输出[object Object] 。我尝试将 golang 的分隔符从{{ }}更改为<<< >>>,但问题没有解决。

Go代码:(我正在使用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 获取数据?如何使用结构元素UnUsedBoxes(这是一个结构数组)?

4

1 回答 1

2

$http.get向服务器发出获取请求以获取 json 数据,而您只是将值直接传递给 js-code。如果我猜对了,您需要将代码更改为

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');
于 2016-07-15T07:26:58.393 回答