Seven steps from Angular.js rookie to expert (2): Scopes

Source: Internet
Author: User
Tags git clone

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.

    1. App.run (function ($rootScope) {
    2. $rootscope.name = "Ari Lerner";
    3. });

Now, we can access the Name property from anywhere in the view, using the template expression {{}}, like this:

    1. {{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:

    1. <div ng-controller="Mycontroller">
    2. {{Person.name}}
    3. </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:

    1. App.controller (' Mycontroller ', function ($scope) {
    2. $Scope.person = {
    3. Name: "Ari Lerner"
    4. };
    5. });

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:

    1. App.controller (' Parentcontroller ', function ($scope) {
    2. $Scope.person = {Greeted:false};
    3. });
    4. App.controller (' Childcontroller ', function ($scope) {
    5. $Scope.sayhello = function () {
    6. $scope.person.greeted = true;
    7. }
    8. });

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:

  1. <div ng-controller="Parentcontroller">
  2. <div ng-controller="Childcontroller">
  3. <input type="text" ng-model="Person.name" placeholder="name"> </input>
  4. <a ng-click="SayHello ()">say Hello</a>
  5. </div>
  6. {{person}}
  7. </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:

    1. var app = angular.module (' myApp ', []);
    2. App.controller (' Playercontroller ', [' $scope ', function ($scope) {
    3. }]);
    4. App.controller (' Relatedcontroller ', [' $scope ', function ($scope) {
    5. }]);

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.

    1. App.controller (' Playercontroller ', [' $scope ', function ($scope) {
    2. $Scope.audio = document.createelement (' audio ');
    3. }]);

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:

    1. App.controller (' Playercontroller ', [' $scope ', function ($scope) {
    2. $scope.playing = false;
    3. $Scope.audio = document.createelement (' audio ');
    4. $scope.audio.src = '/media/npr.mp4 ';
    5. }]);

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:

  1. <div ng-controller="Playercontroller">
  2. <button ng-click="Play ()" class="button" ng-show="!playing">play </button>
  3. <button ng-click="Stop ()" class="button alert" ng-show="playing">stop </button>
  4. Playing Audio: <b>{{Playing}}</b>
  5. </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:

  1. App.controller (' Playercontroller ', [' $scope ', function ($scope) {
  2. $scope.playing = false;
  3. $Scope.audio = document.createelement (' audio ');
  4. $scope.audio.src = '/media/npr.mp4 ';
  5. $Scope.play = function () {
  6. $scope. Audio.play ();
  7. $scope.playing = true;
  8. };
  9. $Scope.stop = function () {
  10. $scope. Audio.pause ();
  11. $scope.playing = false;
  12. };
  13. $scope. Audio.addeventlistener (' ended ', function () {
  14. $scope. $apply (function () {
  15. $scope. Stop ()
  16. });
  17. });
  18. }]);

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:

    1. git clone https://github.com/auser/ng-newsletter-beginner-series.git
    2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.