What is the best way to create a serialized array of objects that can be used as parameters for ng-include
in order to dynamically load data from the server?
Using Angular controller and params with requests:
app.controller("MyCtrl", function($scope) {
$scope.elements = [{"id":43,"grid_id":0,"position":0,"name":"TrescArtykulu","snippet":"","hash_data":{"subname":"Treść artykułu","cache_age":"60","article_id":"15746","category_id":"350"},"element_type":"Plugin"}];
$scope.previewUrl = function() {
// return "elements=" + $.param($scope.elements); // elements=TrescArtykulu=
// GET http://localhost:3000/cms/pages/20/elements=TrescArtykulu= 404 (Not Found)
// return "elements=" + JSON.stringify($scope.PageElementsAttributes); // elements=[{"id":43,"grid_id":0,"position":0,"name":"TrescArtykulu","snippet":"","hash_data":{"subname":"Treść artykułu","cache_age":"60","article_id":"15746","category_id":"350"},"element_type":"Plugin"}]
// GET http://localhost:3000/cms/pages/20/elements=[%7B%22id%22:43,%22grid_id%22:0…5746%22,%22category_id%22:%22350%22%7D,%22element_type%22:%22Plugin%22%7D] 400 (Bad Request)
}
});
Angular view:
<div ng-controller="MyCtrl">
<ng-include src="previewUrl()"></ng-include>
</div>
I found solution:
$scope.previewUrl = function() {
return buildUrl('/cms/pages/preview/', {elements: JSON.stringify($scope.elements)});
}
I'm utilizing the buildUrl()
function extracted from Angular, however I am still unsure how to directly invoke it within MyCtrl without having to manually paste it into my code:
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function (value, key) {
if (value == null || value == undefined) return;
if (angular.isObject(value)) {
value = angular.toJson(value);
}
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}