[英]What is the best way to generate html code after receiving json data from an ajax request using a template library?
[英]Add buttons to html template, after receiving JSON
在用戶訪問站點時從我的 API 接收 JSON 后,我想動態地向 DOM 添加按鈕。 我已經實現了獲取數據的函數,但是現在我在將按鈕動態添加到 HTML 模板時遇到了問題。 此外,我不知道如何在特定模板的第一頁加載時調用函數。
這是我的代碼:
app.run(function($rootScope, $http, ApiService) {
$http.get('connection.properties').then(function (response) {
ApiService.getAllElements($rootScope);
});
});
在我的 ApiService 我有這個功能:
getAllElements : function($scope) {
var requestData = {
'username' : 'user123'
};
this.doRequest(requestData).success(function(data) {
if (data.success) {
console.log(data); // add buttons
}
}).error(function() {
alert('Sorry bro.');
});
}
我是一個完整的 AngularJS 初學者,所以我不知道如何做到這一點的正確方法。 任何幫助將不勝感激。
編輯:
數據 JSON 結構如下所示:
{"success":true,"msg":"user active,1 element in db","userid":"1","elements":[{"element_id":"1","name":"Element1","description":"This is element 1"}]}
在我的 profile.html 模板中,我有這個靜態按鈕:
<div class="btn-group btn-group-elements">
<button type="button" class="btn btn-default" ng-model="element" ng-change="save(true)" btn-radio="'1'">Element1</button>
</div>
你能在這些數據中有多個“元素”嗎? 在這種情況下,ng-repeat 很棒:
初始化你的元素:(在控制器中)
$scope.elements = [];
由於 angularjs 本機指令,將模板鏈接到 $scope :
<div class="btn-group btn-group-elements">
<button ng-repeat="element in elements" type="button" class="btn btn-default" ng-click="doSomething( element, $index )">{{ element.name }}</button>
</div>
獲取數據:
getAllElements : function($scope) {
var requestData = {
'username' : 'user123'
};
this.doRequest(requestData).success(function(data) {
if (data.success) {
$scope.elements = data.elements; // add buttons
}
}).error(function() {
alert('Sorry bro.');
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.