Listening for changes made easy - AngularJS

Hey everyone, I'm experimenting with Angular JS and would love to hear some insights from all you experts out there :D

What I'm currently working on is creating my own localization code. Yes, I know there are existing libraries available, but I prefer building it myself to enhance my understanding of the framework.

I have a select box that lists different languages, and when I switch the language, the terms should be translated accordingly.

Here's the HTML:

    <div ng-controller="LanguageController">
        <div><span>Current Language: {{language}}</span></div>
        <div><span>Term 1: {{dictionary.term1}}</span></div>
        <div><span>Term 2: {{dictionary.term2}}</span></div>
        <div>
            <select ng-model="language" ng-change="changeLanguage(language)">
                <option ng-repeat="(key, value) in lanugages" value="{{key}}">{{key}}</option>
            </select>
        </div>
    </div>

And here's the App.js file:

(function(){
return angular.module('testApp', ['ngRoute'])
    .controller('LanguageController',['$scope',function($scope){
        $scope.lanugages = {
            'English':{
                'term1':'This is Term 1 in English',
                'term2':'This is Term 2 in English'
            },
            'French':{
                'term1':'This is Term 1 in French',
                'term2':'This is Term 2 in French'
            },
            'Vietnamese':{
                'term1':'This is Term 1 in Vietnamese',
                'term2':'This is Term 2 in Vietnamese'
            }
        };
        $scope.language = 'English';
        $scope.dictionary = $scope.lanugages[$scope.language];

        $scope.$watch('language', function() {
            $scope.dictionary = $scope.lanugages[$scope.language];
        });

        $scope.changeLanguage = function(lang){
            $scope.language = lang;
        }

    }]);
})();

I've included a $watch statement to monitor changes in the language variable and update the dictionary accordingly.

I'm curious if there's a more advanced method to track changes in language and update

dictionary</code without relying on <code>$watch
.

Thanks for your help! :D

-M

Answer №1

Edit: addressing the feedback received, here is an alternative version available at this link: http://jsfiddle.net/dn3w41cx/9/

No need for data manipulation in the controller.

Check out the following code snippet:

javascript

function LanguageController($scope) {
    $scope.languages = [
        {
            name:'English',
            'term1': 'This is Term 1 in English',
                'term2': 'This is Term 2 in English'
        },
            {
                name:'French',
            'term1': 'This is Term 1 in French',
                'term2': 'This is Term 2 in French'
        },
             {
                 name:'Vietnamese',
            'term1': 'This is Term 1 in Vietnamese',
                'term2': 'This is Term 2 in Vietnamese'
        }
    ];

}

html

<div ng-app>
    <div ng-controller="LanguageController">
        <div><span>Current Language: {{language.name}}</span>
        </div>
        <div><span>Term 1: {{language.term1}}</span>
        </div>
        <div><span>Term 2: {{language.term2}}</span>
        </div>
        <div>
            <select ng-options="item.name for item in languages" ng-model="language" 
                    ng-init="language=languages[0]">
            </select>
        </div>
    </div>
</div>

Past answers:

To have a clean syntax, consider integrating something similar to the changeLanguage function presented in this fiddle: http://jsfiddle.net/dn3w41cx/6/

Alternatively, you can achieve this without additional javascript changes as demonstrated in this fiddle: http://jsfiddle.net/dn3w41cx/5/

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

Saving a picture to local storage with the file input type in ReactJS

I am attempting to save an image in the browser storage once a user selects an image from their computer. <div className="add_grp_image_div margin_bottom"> <img src={img_upload} className="add_grp_image"/> <input type="file" class ...

Issues occurring with PhoneGap preventing the execution of AngularJS code

I've recently delved into learning AngularJS with PhoneGap and I have a basic HTML code along with some AngularJS snippets. While everything runs smoothly in the browser, only the HTML portion seems to work when I attempt to run it on my Android phone ...

Unable to load Google charts within an Angular application

Here is an excerpt from the controller for the page I am loading, written in coffeescript. When data is received from the server, it is transformed into a json array of arrays. The method onChartDataReady is then called, which loads 3 files via the jsapi w ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

Exploring the depths of Master-Detail functionality with Ionic and Angular, unlocking nested

Hey there! I'm currently working on a project using Ionic and Angular, where users can view events and see all the attending participants along with their information. To achieve this, I implemented a master-detail pattern within another master-detail ...

Include a script tag in a React component in NextJS without relying on props or context

Currently, I am trying to include a library in my React component using a script tag. My approach involves calling an API in an _app.tsx file and then accessing the result in a _document.tsx file. In the _document.tsx file, I add the script tag to the docu ...

Styling for Print Media: Adjusting the horizontal spacing between inline elements

I have been developing a custom AngularJS point-of-sale (POS) system that requires printing receipts upon completing a sale. To achieve this, I am using ng-print to print out a sales summary displayed within a specific div element after hiding all other un ...

Detecting modifications to an array with MobX

Today marks my first foray into learning MobX and I am eager to discover how to track all array changes (insertions, deletions, etc) with MobX. A practical example would definitely help clarify this: const TodoList = ({todos}) => ( <ul> ...

Encountering a 404 server error on Azure Node.js web app while running AngularJS 1.6.x with lengthy URLs

My current setup includes two azure web apps deployed with a node.js express server and using angularjs (1.6.x) for the MVC (ui-router). One web app links directly to the other, passing an access token in the query params for authentication. Everything run ...

Tips for integrating Vue code into the <code> tag within Vue applications

I am venturing into creating my first npm package and am currently working on the package's demo. I want to showcase an example of how to use the component. However, when I include the component usage within the pre and code tags as shown below: I e ...

Use Angular to send an array to a Django view by utilizing the $http.post method

I am trying to make a post request to a django view with the following code: $http({ method: "post", url: "/enterprises/vouchers/_send", data: { group_id: group_id, group_student_ids: [1, 2, 3, 4] } ...

Looking for a way to receive a callback once the rows have been filtered while utilizing ng-repeat in conjunction with a filter in

Currently, I am utilizing angularjs and ng-repeat to populate the necessary data in the datagrid. It looks something like this: <input type="text" placeholder="Search" ng-model="query"> <tr ng-repeat="item in items | filter:query"> <td> ...

Visibility issue in Three.js: Object not appearing immediately despite setting object.visible to true

I'm toggling visibility in my Three.js scene by using the .visible property on objects. Initially, certain objects (rooms) have their .visible property set to false. Once the camera enters a specific mesh (the room bounding box), the .visible propert ...

How can you convert a JavaScript object with nested arrays into JSON format?

I have been working with a JavaScript object that contains nested objects with associative arrays. I attempted to use the stringify function from the json2.js library, but the output did not include the arrays inside the nested objects. In my scenario, I b ...

Utilizing a function that changes a UNIX timestamp to a month/day/year layout

I have been working with ExpressJS and am facing a challenge in converting the UNIX format date to mm/dd/yyyy format when retrieving the date value. I attempted to create a function for this conversion, but encountered an issue where my methods cannot be c ...

A helpful guide on how to separate text using Java Script and the "/" character

Just diving into the world of JavaScript and encountering some challenges with splitting text. The string that needs to be split looks like this: mobile)/index.m3u8 The desired output should be: mobile and index.m3u8 I attempted to use .split("&bso ...

What is the best way to display a placeholder instead of the state's value when a page loads?

I'm having trouble displaying the placeholder of an input instead of its state value. When the page loads, it shows an empty select box because the testType state is null initially. How can I make sure that only the placeholder is shown instead of the ...

What is the best way to create a new object in a Vue component with optimal efficiency?

Currently, I am working on initializing a map that would be utilized in my calculatePrice function. calculatePrice(key) { let prices = new Map({ 0: 17, 1: 19, 2: 24, 3: 27, 4: 30, 5: 46, 6: 50 ...

You can't retrieve a JSON object using Javascript

Every time I execute the javascript/php code below, I encounter an issue where I keep receiving "undefined" when trying to alert the 'userid' property of the json object. However, if I turn the json object into a string using stringify(), it corr ...

Make sure to place the <i> tag within the <li> tag at the bottom to automatically resize the height

Currently, I am working on customizing my menu design with a mix of bootstrap and font awesome CSS styles. It would be easier to demonstrate the issue on a live page. My main objectives are two-fold: I want to position the chevron icon at the bottom with ...