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:
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:
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
:
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:
Add one more Text
component outside the Accordion
component and set ng-model
to firstName
:
Test the app again. You’ll see that the Text
component outside the Accordion
component doesn’t change its value yet:
Let’s find out how this can be changed. Go to Project
-> Model
and create model Main
:
Go to Scope
and create a variable called main
of type Main
:
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:
Add the last Text
component outside the Accordion
component with text Second name: {{main.secondName}}
and test the app again.
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.