Understanding How to Work with AngularJS Scope Variables

Posted: November 16th, 2015Author:

AngularJS greatly simplifies mobile app development. At the same time, it introduces a number of important concepts that you need to understand in order to create apps quickly. One of the important concepts is working with the scope object and the variables you place in the scope. In this post we are going to show you how to access variables placed in the scope.

Let’s create a simple app to clarify this concept. The app is going to look like this:


Ionic app with Accordion component

To start, place the Accordion component on the page. Rename item1 to First name and item2 to Second name. Put the Input components in each cell and change the corresponding text in the placeholders to Enter First Name and Enter Second Name. The page should look like this:

Designing the page

Next, place the Text component in the first cell with the text First name: {{firstName}}. For the Input component, set the ng-mode property to firstName:

Binding UI to scope

Let’s now test the app. Click the Test button in the App Builder to launch the app in the browser. When you enter any text in the input field, it will show in the label field below it:

Testing the app

Add one more Text component outside the Accordion component and set ng-model to firstName:


Updating the UI

Test the app again. You’ll see that the Text component outside the Accordion component doesn’t change its value yet:


Testing the app

Let’s find out how this can be changed. Go to Project -> Model and create model Main:


Creating app model

Go to Scope and create a variable called main of type Main:


Adding a variable to scope

Switch back to the Design view and add the third Text component in the second cell. Change it to Second name: {{main.secondName}}. Set ng-model to main.secondName for the second input:


Binding the UI to scope

Add the last Text component outside the Accordion component with text Second name: {{main.secondName}} and test the app again.


Testing the app

The text changes in both Text components. It is one of the main principles of working with complex components in AngularJS. You can find more information about it here and here.