Understanding How to Work with AngularJS Scope Variables

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:

2015-10-21_1228

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:

4

Updating the UI

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

5

Testing the app

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

6

Creating app model

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

7

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:

8

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.

9

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.