Considerations for using Angular.js development _angularjs

Source: Internet
Author: User
Tags eval getdate

Objective

Recently has been playing angularjs, have to say, compared to knockout,angularjs this MVVM framework is more powerful, and more complex, various tutorials online everywhere, but the real use of the project will encounter a variety of pits.

First, Ng-repeat

Ng-repeat is used to identify a elem that requires duplicate output, while the contents of the duplicate output need to be unique

<div ng-app= "App" ng-controller= "Control" >
  

Let app = Angular.module ("App", []);
App.controller ("Control", ($scope) => {
  //output Li Mi
  $scope. repeatcontent = ["Li", "Bin", "Wang"];
  Below there are two "Wang", will be an error
  //$scope. repeatcontent = ["Li", "Shore", "Wang", "Wang"];
})

Second, provider, service, factory relationship between

Factory

Factory is very much like service, except that service is a single instance object in angular, that is, when a service is needed, the new keyword is used to create a service. And factory is a normal function, when needed, he is just a normal function of the invocation, it can return various forms of data, such as by returning a function of the collection object to be used.

Defined:

Let app = Angular.module ("App", []);

Here you can inject $http and other Provider
app.factory ("Today", () => {let
  date = new Date ();
  return {
    year:date.getFullYear (),
    month:date.getMonth () + 1,
    day:date.getDate ()
  };
});

Using injection:

App.controller (' Control ', (today) => {
  console.log (today.year);
  Console.log (today.month);
  Console.log (Today.day);
});

Service

Service is used as a single object, and it is also a constructor, which features that it can not return anything because it uses the New keyword to create a new one, and it can interact with the data using the controller communication, because controller The scope chain is destroyed when it is not available (for example, using routing to jump to another page with another controller)

Defined:

Let app = Angular.module ("App", []);

Here you can inject $http etc Provider
//Note that the arrow function
//arrow function cannot be used here as constructor
App.service ("Today" , function () {Let
  date = new Date ();
  This.year = Date.getfullyear ();
  This.month = Date.getmonth () + 1;
  This.day = Date.getdate ();
});

Using injection:

App.controller (' Control ', (today) => {
  console.log (today.year);
  Console.log (today.month);
  Console.log (Today.day);
});

Provider

Provider is the basic way to create service, you can understand that provider is a configurable version of the service, we can provider before the formal injection of the provider parameters of the configuration.

Defined:

Let app = Angular.module ("App", []);

Here you can inject $http etc Provider
//Note that the arrow function
//arrow function cannot be used here as constructor
App.provider ("Today ", function () {
  this.date = new Date ();
  let self = this;

  This.setdate = (year, month, day) => {
    this.date = new Date (year, month-1, day);
  }

  this. $get = () => {return
    {
      year:this.date.getFullYear (),
      month:this.date.getMonth () + 1,
      day : This.date.getDate ()};;}
);

Using injection:

It's reconfigured here today's date is February 15, 2015
//Note that this is injected with Todayprovider, using the hump name to inject the correct provider app.config that needs to be configured
( Todayprovider) => {
  todayprovider.setdate (2015, 2);
});

App.controller (' Control ', (today) => {
  console.log (today.year);
  Console.log (today.month);
  Console.log (Today.day);
});

Three, handlebars and angular symbol resolution conflict

Scene:

When I use Node.js as the service side, which uses the handlebars as the template engine, when node.js corresponds to a URL and render it, because its template uses {{}} as a variable resolution symbol. Similarly, angular uses {{}} as a variable to parse the symbol, so when node.js render the page, if the variable in {{}} does not exist, the area is emptied, and my intention is to use this as a angular parse instead of Handleb ARS, and I want to continue using handlebars, then I need to redefine the angular default {}} resolution symbol. Even though the dependency injection $interpolateProvider is defined, the following example:

App.config ($interpolateProvider => {
  $interpolateProvider. Startsymbol (' {');
  $interpolateProvider. Endsymbol ('}]} ');

Four, Ng-annotate-loader

Ng-annotate-loader application to Webpack + angular development scenario, is used to solve angular in the JS compression caused by dependency injection failure and error resolution

Installation

$ NPM Install Ng-annotate-loader--save-dev

Configuration

Webpack.config.js
{
  test:/\.js?$/,
  exclude:/(node_modules|bower_components)/,
  loader: ' Ng-annotate!babel?presets=es2015 '
},

Five, two-way data binding

When we use a angular event, the data change in $scope does not cause a $digest dirty-checking loop, which causes the view not to sync when the model changes, and then we need to initiate the update ourselves.

Html

<div>{{foo}}</div>
<button id= "Addbtn" >go</button>

Javascript

App.controller ("Control", ($scope) => {
  $scope. foo = 0;
  document.getElementById ("Addbtn"). AddEventListener ("click", () => {
    $scope. foo++;
  }, False)

Obviously, the intention of the example is that when you click the button, Foo grows and updates the View, but in fact, $scope. Foo is changed, but View does not refresh, because Foo does not have a $watch detect changes after $apply, resulting in $digest , so we need to trigger $apply or create a $watch to trigger or detect data changes

JavaScript (using $apply)

App.controller ("Control", ($scope) => {
  $scope. foo = 0;
  document.getElementById ("Addbtn"). AddEventListener ("click", () => {
    
    $scope. $apply (function () {
      $ scope.foo++)
    ;}

  , false);

JavaScript (using $watch & $digest)

App.controller ("Control", ($scope) => {
  $scope. foo = 0;
  $scope. flag = 0;

  $scope. $watch ("Flag", (NewValue, OldValue) => {

    //when $digest loops detect flag, the function is called if the new old value is inconsistent
    $scope. foo = $scope. fl AG;
  });

  document.getElementById ("Addbtn"). AddEventListener ("click", () => {
    
    $scope. flag++;
    Active triggering $digest loop
    $scope. $digest ();
  }, False);

Vi. $watch (watchexpression, Listener, [objectequality])

Registers a listener callback function that is invoked each time the value of the watchexpression changes

Watchexpression is invoked every time the $digest executes and returns the value to be detected (when the same value is entered multiple times, watchexpression should not change its own value, or it may cause multiple $digest loops. Watchexpression should be idempotent)

Listener will be invoked when the current watchexpression return value is inconsistent with the last Watchexpression return value (using!== to strictly determine the inconsistency, rather than using = = to judge, but objectequality = = True Except

Objectequality is a Boolean value, and when True, the angular.equals is used to determine consistency, and angular.copy is used to save this copy of the object for the next comparison, which means that complex object detection will have Performance and memory problems

Vii. $apply ([exp])

$apply is a function of the $scope that triggers the $digest loop

$apply Pseudo Code

function $apply (expr) {
  try {return
    $eval (expr);
  } catch (e) {
    $exceptionHandler (e);
  } finally { c9/> $root. $digest ();
  }

Use $eval (expr) to execute an expression of expr

If you run out of exception during execution, execute $exceptionHandler (e)

Finally, regardless of the result, the $digest loop is executed once

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

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.