Tips for converting an object into parameters for ng-include

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('&');
}

Answer №1

If you want to generate a URL from an object in AngularJS, you can create a sample function like the one below:

$scope.objectToUrl = function(obj) {

    var ret = [];
    for (var d in obj) {    
      ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(obj[d]));    
    }    
    link = ret.join("&");
    return link
  }

Check out the demo code snippet provided:

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {


  $scope.urlObject = {
    "id": 43,
    "grid_id": 0,
    "position": 0,
    "name": "TrescArtykulu",
    "snippet": "",
    "element_type": "Plugin"
  };

  $scope.objectToUrl = function(obj) {

    var ret = [];
    for (var d in obj) {

      ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(obj[d]));

    }

    link = ret.join("&");
    return link
  }
  $scope.test = "a"

  $scope.link = $scope.objectToUrl($scope.urlObject);

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div ng-app="app">
  <div ng-controller="homeCtrl">
Your object<pre>{{urlObject| json}}</pre>

    <h4>
    Your  url: {{link}}
      </h4>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

The combination of Chromium, raw HTML pulled directly from a C# string, and Angular leads to issues when trying to implement routing

CefSharp: 1.25.0 (Chromium 25.0.1364.152-based) Angular: 1.3.0-beta16 UIRouter: 0.2.10 Currently, I am in the process of creating a C# application that will function as a standalone program using CefSharp Chromium, Angular, and UIRouter for the graphical ...

Flag a specific property on a directive scope as needing an update

Recently, I made the switch to using AngularJS in a web application that was previously mostly jQuery based. One of the components in this app utilizes jQuery UI's draggable feature, which relies on the CSS left property for positioning objects during ...

Is the second parameter of the function being used as a condition?

Why is it necessary to validate the helpText argument within the function to be non-equative to null when its ID is linked with the span tag? The functions task is to set and clear help messages in the form field using built-in CSS classes. <input id ...

Adding two comparable Objects in Javascript / vuejs

I have two objects and I want to add the values of each key separately with another object. Here's an example: CharacterStats: { a: 0, b: 2, c: 0, d: 0 } ItemStats: { a: 0, b: -1, c: 4, d: 0 } The expected result is: CharacterStats: { a: 0, b: 1, c: ...

Interacting with wpdb using AngularJS

I just started learning AngularJS and I'm eager to implement it on my WordPress website. My goal is to display a table with data from a database in my WordPress site, but I am encountering difficulties accessing the WordPress functions and variables. ...

Selenium webdriver cannot find the element within the JavaScript code

await driver.findElement(By.id('closeBtn')).click(); or await driver.findElement(By.xpath('//*[@id="closeBtn"]')).click(); When attempting to use the above conditions for a pop-up, it does not work as expected. An error is ...

Is there a way to retrieve a label's text using their class name within a loop?

I have multiple labels sharing the same classname, each with different text. My goal is to iterate through them and extract the text they contain. Here is the example markup: <label class="mylabel pull-left"> Hello </label> <label class="m ...

Iterating through an object in Javascript using dynamically changing property names

Is there an efficient way in Javascript to iterate through the property names of objects in an array? I have objects with properties from guest1 to guest100. Instead of manually looping through each property, is there a method to loop through all the gues ...

The request payload appears as [Object Object] when initiating the AJAX post request

Currently, I am making an AJAX request with the specified data. The data being sent is an object and my intention is to send the object itself without converting it to a JSON string. However, when viewing the request in the browser, the payload is shown as ...

Error: The JSONP request encountered an unexpected token, causing a SyntaxError

Asking for data using AJAX: $.getJSON('https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD&callback=?', function(result) { console.log(result); }); Encountering an error: "Uncaught SyntaxError: Unexpected token :" ...

The Role of Filling in a Process

I am looking to create a rectangle that fills up gradually every day, increasing by 1% each time. This is the basic concept. My main struggle is figuring out how to fill it up. I need the rectangle to increase by 1% of its width each day. So essentially, ...

JavaScript Arrays are not functioning properly within the Poo constructor

Attempting to insert data into a JavaScript Array within my constructor has resulted in this error message: TypeError: this.listeetudiant is undefined This is my constructor: function Cours(){ */the array causing trouble: */ this.listeetudiant=[]; */ ...

Merging an AppBar and Drawer in Material UI for a seamless user interface design

I am working on integrating an AppBar component with a drawer feature. Here is the code for the AppBar: import React from "react"; import PropTypes from "prop-types"; import { withStyles } from "material-ui/styles"; import AppBar from "material-ui/AppBar" ...

Avoid receiving input for a button that is being covered by another button

I am currently developing an Idle Game and I am looking to include 'buy buttons' for purchasing buildings, along with a sell button embedded within the buy button. Just as a heads up, these buttons are represented by DIVs acting as buttons. Here ...

Is it possible to retrieve a JSON response by making a jQuery.ajax request to an appengine URL?

Attempting to retrieve response data via ajax from the following URL: http://recipesid.appspot.com/api.user?method=user.query&[email protected] Encountering issues when trying to run the code. Please assist in resolving this problem. $.ajax({ ...

HTML table row content should be aligned to the left side

I am attempting to align the data in the 'Address' column without any margin. I want it to start from the left since it's overflowing. You can find the HTML, CSS, and JS code here Even though I tried using <td align="left">..</td& ...

Merging double borders in a div using CSS is essential for creating

Upon examining this sample, it's evident that the borders do not blend together. css: div{ float:left; background-color:moccasin; width:100px; height:100px; border:1px solid tomato; } The number of divs is arbitrary, and only on ...

The maximum value of the slider corresponds to the total number of elements in the array

As I work on constructing a Material UI Slider, I have a specific requirement. I want the maximum value of my slider to dynamically adjust according to the number of items in an array of options. ['Answer1', 'Answer2', 'Answer3&ap ...

Encountering an issue in XtermJS where it is unable to read properties of undefined, specifically 'dimensions', while being used with NextJs version 14

UPDATE: Additional Details useEffect(() => { // let terminal; if (terminalRef.current) { const terminal = new Terminal({ fontFamily: "Menlo, Monaco, monospace", // fontSize: 12, // cursorBlink: true, ...