Leveraging Angular translate in the controller to handle data retrieved by a service

Let me present you with a specific scenario:

My data is stored in a JSON file and it looks like this:

"IOS_TABLET_DOWNLOAD_URL": {
  "type": "string",
  "minLength": "5",
  "title": "IOS_TABLET_DOWNLOAD_URL",
  "description": "$filter('translate')('configuration.IOS_TABLET_DOWNLOAD_URL')"
},

The challenge I am facing is with the translation of the description field using Angular Translate. In order to achieve this, I am injecting the service into my controller as shown below:

ConfigController.$inject = ['$scope', '$filter', '$compile', 'MyService'];
function ConfigController($scope, $filter, $compile, MyService) {

  // Utilizing the compile function
  $scope.schema = elements; // 'elements' is an object fetched from MyService
  $compile($scope.schema)($scope);

}

Despite my efforts, the $filter is not being processed as expected and is being displayed as it is in the view:

"$filter('translate')('configuration.IOS_TABLET_DOWNLOAD_URL')"

UPDATE

In my case, I am using Angular Schema Form for form generation. This results in a structure like the following in the view:

<div ng-controller="FormController">
   <form sf-schema="schema" sf-form="form" sf-model="model"></form>
</div>

What steps should I take to overcome this issue?

Answer №1

If you want to see the full working fiddle, you can visit https://jsfiddle.net/dqhwzksx/. However, I will break down the important sections here for easier understanding.

The issue arises because both angular-schema-form and angular-translate do not recognize

"description": "$filter('translate')('configuration.IOS_TABLET_DOWNLOAD_URL')"
on their own. We need to handle the translation ourselves.

Firstly, our schema no longer needs to handle the filter internally:

var schema = {
    "type": "object",
    "title": "Sample Schema",
    "properties": {
        "IOS_TABLET_DOWNLOAD_URL": {
          "type": "string",
          "minLength": "5",
          "title": "IOS_TABLET_DOWNLOAD_URL_TITLE",
          "description": "IOS_TABLET_DOWNLOAD_URL_DESCRIPTION"
        }
    }
};

The title and description fields can now directly reference the translation tokens. Next, we will create an angular service that fetches this schema with translations already applied. This seems to be the purpose of your MyService:

.factory('Schema', function ($q, $translate) {
    return {
        elements: function() {
            var a = [];
            var result = angular.copy(schema);
            angular.forEach(result.properties, function (value, key) {
                a.push($translate([value.title, value.description]).then(
                    function (translations) {
                        value.title = translations[value.title];
                        value.description = translations[value.description];
                    }
                ));
            });
            return $q.all(a).then(function() { return result; });
        }
    }
})

Breaking it down:

var a = [];
var result = angular.copy(schema);

We initiate an array a to store promises (one for each field in the schema) and make a copy of the original schema since we will modify it.

angular.forEach(result.properties, function (value, key) {
    a.push($translate([value.title, value.description]).then(
        function (translations) {
             value.title = translations[value.title];
             value.description = translations[value.description];
        }
    ));
});

We iterate over each property in the schema, request translations for the title and description fields, and update the schema copy with the translations. Promises are added to the a array to keep track of translations.

return $q.all(a).then(function() { return result; });

Finally, we wait for all promises to resolve (translations completed) and return the fully translated schema object.

.controller('FormController',function ($scope, Schema) {

    Schema.elements().then(function (elements) {
        $scope.schema = elements;
    })
    $scope.model = {};
    $scope.form = [
        "IOS_TABLET_DOWNLOAD_URL"
    ];

});

The controller remains simple, similar to the original, and the template markup remains unchanged.

For a change, try switching the preferred language to de from en:

$translateProvider.preferredLanguage('de');

EDIT

If you wish to fetch the schema from an external file or service, replace the elements method with something like:

elements: function() {
    return $http.get('path/to/schema.json').then(function(response) {
        var a = [];
        var schema = response.data;
        angular.forEach(schema.properties, function (value, key) {
            a.push($translate([value.title, value.description]).then(
                function (translations) {
                    value.title = translations[value.title];
                    value.description = translations[value.description];
                }
            ));
        });
        return $q.all(a).then(function() { return schema; });
    });
}

Answer №2

It suddenly dawned on me that the description attribute is strictly a string. It seems logical that it would only display text content. JSON is primarily designed for transmitting data, not functions (otherwise it would just be plain JavaScript). Simply provide the data you wish to refine and substitute it with the desired output.

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

What are the steps to create a new website with a MEAN stack application on a Windows 10 home computer?

A few days ago, I successfully installed the MEAN stack application on my Windows 10 system. However, I am unsure of how to proceed with creating a new website using this MEAN stack application. Can anyone provide guidance on how to go about building a w ...

Converting CSDL format into JSON data structure

Is there a way to convert data retrieved in CSDL format from an Oracle DB into JSON format using NODE JS? export async function getRecepFarma(req: Request, res: Response): Promise<Response> { const conn = await connect(); const result = await ...

JQuery allows for multiple drag and drop functionalities, including events that occur after an object

I'm currently working on a .php page where I need to implement a drag-and-drop functionality. There will be 3 draggable elements that must be placed in their corresponding droppable elements - each draggable can only be dropped in a specific droppable ...

What is the best way to change PHP database information into JSON format while using custom titles for each column?

Is it possible to convert PHP data sent from a controller to a view into JSON objects with new titles, and then wrap it in a script tag? I want the data to have the same titles as specified in my view, even though the database titles are different. Contro ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

What is the best way to save and retrieve JSON information in MySQL databases?

How can I efficiently store and retrieve JSON data in MySQL using PHP? mysql_query("INSERT INTO text (data) VALUES (json_encode('id' => $uid, 'value' => yes))"); After that, how do I update the data value? Should I read the data ...

What are the essential files needed in Kendo UI Core for a mobile app?

Several months ago, I created a trial Kendo mobile app but now I want to verify it using the most recent version of Kendo UI Core. In my previous project, I referenced the following files: <link href="../styles/kendo.common.min.css" rel="stylesheet" / ...

Is it possible to leverage both functions and variables within the ng-options expression in Angularjs?

I am faced with a situation where I have 2 select boxes. The first one is used to choose the user type (such as groups or individual), and the second one displays the options based on the selection made in the first box. I was wondering if it is possible t ...

The most efficient way to invoke a jws void method in the fewest steps possible

When calling a void method of a SOAP JWS web-service using JavaScript without expecting a result back, what is the most efficient and concise approach? ...

Tips for eliminating unnecessary databinding in AngularJS

I have a web page built with AngularJS that allows me to edit fields by loading data from the database, making changes, and then saving the updated information back to the database. The API for the database requires me to submit both the existing data an ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

What could be causing the directives module to not get properly incorporated into the Angular app module?

I am currently in the process of learning Angular and have come across some challenges with module resolution. In js/directives/directives.js, I have a directive scoped within a directives module: angular.module("directives").directive("selectList", funct ...

Why does the browser indicate that a GET request has been sent but the promise does not return anything?

Having trouble with a puzzling issue and unable to find any solutions online. I am attempting to make a basic HTTP get request to receive a JSON object from an API I created (using express+CORS). I have experimented with both Axios and VueResource, yet en ...

Generating a JSON object by combining data from different JSON paths

Our task is to generate a JSON object using the provided JSONPaths. For instance, we have two paths and their corresponding values that should be included in the new JSON object: $.student.firstName = "Abc" $.student.subject['physics']. ...

Use Python to enter a value on a webpage coded in HTML

My current project involves automating the input of values into a webpage. However, I have encountered a significant hurdle with the Mechanize library as it does not recognize the forms on my page which are <input> elements, unlike the typical form.n ...

"Performing a series of getJSON requests with a delay between each call, iterating through an array

Could someone shed light on why my jQuery/JavaScript code runs with an unexpected flurry of ajax calls instead of at a steady 1-per-second rhythm? var i = 0, l = data.length; function geocode() { $.getJSON( 'https://maps.googleapis.com/maps/api ...

Transforming JSON data into a PowerShell object and vice versa

After exporting the JSON data from an Azure Resource Group to a file using this command: Export-AzureRmResourceGroup -ResourceGroupName $SourceResourceGroupName -Path $filename I retrieve the JSON content from the file and assign it to a variable like so ...

Exploring typeahead functionality with JSON and arrays structure

I'm facing an issue where I need to generate a json file from an sql query and utilize it with twitter typeahead. However, the current json format is not fitting the requirements for typeahead. The expected json format should look like this; [' ...

Spring Boot REST API showcases the response outcomes in a specific format

I am looking to format the response result in a specific way: [ "author":"Author", "status_code":"200" "message":"GET", "description":"Description..." "data":{ &q ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...