This is the second chapter of the "AngularJS-seven step from rookie to expert" series.
In the first article we showed how to start building a angular application. In this article, we discuss a basic concept necessary to understand how ANGULARJS works, and how you can better use it.
In this series of tutorials, we will develop an audio player for NPR (National Public Radio), which will show the latest stories that are now aired on the Morning edition program and play them in our browser. Complete version of the demo can be seen here.
Part II Scopes
$scope is an object that links a view (a DOM element) to a controller. In our MVC structure, this $scope will be the model that provides a excecution context bound to the DOM element (and its child elements).
Although it may sound complicated, $scope is actually a JavaScript object that both controller and view can access, so we can use it to pass information between the two. In this $scope object, we store both the data and the functions that will run on the view.
Every angular application will have a $rootScope. This $rootScope is the top-level scope, which corresponds to the DOM element that contains the Ng-app Directive attribute.
If the page is not explicitly set $scope, Angular will bind the data and functions here, the first part of the example is to run successfully.
In this example, we will use $rootScope. In the Main.js file, we add a name attribute to this scope. By putting this function in the App.run function, we guarantee that it will be executed before other parts of the application. You can think of the App.run function as the main method of the angular application.
- App.run (function ($rootScope) {
- $rootscope.name = "Ari Lerner";
- });
Now, we can access the Name property from anywhere in the view, using the template expression {{}}, like this:
- {{Name}}
In the later chapters of this series, we'll go into the syntax of template expressions.
Please see:
Ari Lerner
Anyway:
To really see the power of scope, let's add a controller to a DOM element that will create the $scope of this element and let us interact with this element.
Ng-controller
To explicitly create a $scope object, we are going to put a controller object on the DOM element, using the Ng-controller Directive attribute:
- <div ng-controller="Mycontroller">
- {{Person.name}}
- </div>
The G-controller directive creates a new $scope object for the DOM element in which it is located, and includes the $scope object in the $scope object of the outer DOM element. In the above example, the $scope object of this outer DOM element is the $rootscope object. This scope chain is like this:
Now, Mycontroller has created a $scope object that can be accessed directly from within the DOM element. Here we create a person object in this $scope, in Main.js:
- App.controller (' Mycontroller ', function ($scope) {
- $Scope.person = {
- Name: "Ari Lerner"
- };
- });
Now we can access this person object in any child element of the DOM element that has the ng-controller= ' Mycontroller ' property, because it is on the $scope.
Please see:
Ari Lerner
Except for one exception, all scopes follow the stereotype inheritance (Prototypal inheritance), which means that they all have access to the parent scope. For any property and method, if the ANGULARJS is not found on the current scope, it will go to the parent scope to find, if not found on the parent scope, will continue to backtrack upward, until $rootscope.
The only exception: some directive attributes can optionally create an independent scope, so that the scope does not inherit its parent scope.
For example, suppose we have a parentcontroller that contains a person object and another Childcontroller want to access this object:
- App.controller (' Parentcontroller ', function ($scope) {
- $Scope.person = {Greeted:false};
- });
- App.controller (' Childcontroller ', function ($scope) {
- $Scope.sayhello = function () {
- $scope.person.greeted = true;
- }
- });
When we bind Childcontroller to Parentcontroller in the view, we can access the properties of the parent scope created by Parentcontroller in the child element, like accessing Childcontroller The same as the properties in your scope:
- <div ng-controller="Parentcontroller">
- <div ng-controller="Childcontroller">
- <input type="text" ng-model="Person.name" placeholder="name"> </input>
- <a ng-click="SayHello ()">say Hello</a>
- </div>
- {{person}}
- </div>
Please see:
Combined into MyApp
Now, let's use $scope on our NPR app. At the end of the previous chapter we defined the app module, and now we're going to go deep into the DOM structure and create basic functionality.
As shown in the example above, we first create a root controller, named Playercontroller. There is also a relatedcontroller, which will be responsible for managing audio DOM elements, and retrieving the list of NPR programs for us.
Back to Main.js, now we're going to create these two controllers:
- var app = angular.module (' myApp ', []);
- App.controller (' Playercontroller ', [' $scope ', function ($scope) {
- }]);
- App.controller (' Relatedcontroller ', [' $scope ', function ($scope) {
- }]);
Audio
These two controllers are not yet functional, so let's add some sound to the app. In this tutorial we will use HTML5 's audio DOM element, so first you have to have a browser that supports HTML5 (we recommend Google Chrome).
This audio DOM element, we can add it in HTML, but also in our controller. But since we primarily use controllers to interact with this audio DOM element, it is more appropriate to create it in a controller.
Now we're going to create an audio DOM element in the Playercontroller. We're going to store it on scope and then--as you've learned--connect the view and the controller with the $scope object.
- App.controller (' Playercontroller ', [' $scope ', function ($scope) {
- $Scope.audio = document.createelement (' audio ');
- }]);
This setting may be a bit boring now, because it can't do it yet. We will introduce the "Retrieve (fetching)" Data in the next section of this series, and now we'll start with a specified. mp4 URL.
Or in this playercontroller, specify the SRC attribute of the audio file as a. mp4 URL that you can access. For convenience, we're using an NPR audio file stored on our own server here, but you can point to any URL. Now set your audio src address as follows:
- App.controller (' Playercontroller ', [' $scope ', function ($scope) {
- $scope.playing = false;
- $Scope.audio = document.createelement (' audio ');
- $scope.audio.src = '/media/npr.mp4 ';
- }]);
Try
Play Playing Audio: false (Please test "play" button in English original)
The audio doesn't play itself, we have to let it play. To do this, we can simply use $scope.audio.play () and then HTML5 the audio DOM element to start playing the MP4 media stream.
We can provide an interactive element to the user: Create a button and bind it to an action in the $scope. In the next article we will introduce this piece in more detail, but first look at the HTML in the example above:
- <div ng-controller="Playercontroller">
- <button ng-click="Play ()" class="button" ng-show="!playing">play </button>
- <button ng-click="Stop ()" class="button alert" ng-show="playing">stop </button>
- Playing Audio: <b>{{Playing}}</b>
- </div>
Note that we do not need to refer to the audio DOM element created in scope because it was created with document.createelement ("audio") inside the controller when we loaded the controller. In the following tutorial we will refactor this section because it is generally not a good idea to manipulate DOM elements in a controller (thanks to Brad Green for pointing this out in the comments). For the sake of simplicity, however, we are still here to keep this controller.
We've added some variables to the view, and we're going to manage the variables on the $scope. Here are some high-level concepts that will be detailed in the tutorials later in this series, so don't worry if you don't see it all at once:
- App.controller (' Playercontroller ', [' $scope ', function ($scope) {
- $scope.playing = false;
- $Scope.audio = document.createelement (' audio ');
- $scope.audio.src = '/media/npr.mp4 ';
- $Scope.play = function () {
- $scope. Audio.play ();
- $scope.playing = true;
- };
- $Scope.stop = function () {
- $scope. Audio.pause ();
- $scope.playing = false;
- };
- $scope. Audio.addeventlistener (' ended ', function () {
- $scope. $apply (function () {
- $scope. Stop ()
- });
- });
- }]);
The above is the introduction of the $scope function of Angular.js. In the next chapter, we'll cover two-way data binding for angular.js.
The official code base for this series can be downloaded from github:
Https://github.com/auser/ng-newsletter-beginner-series.
To save this code base locally, make sure you have installed Git,clone this codebase and check out the Part2 branch:
- git clone https://github.com/auser/ng-newsletter-beginner-series.git
- Git checkout-b part2
Original link: http://www.ng-newsletter.com/posts/beginner2expert-scopes.html
Link: http://blog.jobbole.com/48593/
Seven steps from Angular.js rookie to expert (2): Scopes