前端- angularjs知识点

前端- angularjs知识点

Data Model Binding

one way

{{}}` same as ng-bind `Hello {{name}}</span>

two way

ng-model bind

DI

Dependency Injection

Router

Frontend handle routing, key feature of SPA

Directive

manipulate dom - resuable

build-in directive

(ng-??)

  • ng-repeat
  • ng-model
  • ng-bind
  • Ng-show
  • ng-class
  • Etc...

bootstrap: ng-app, ng-controller, ng-module

Customize Directive

Check Directive secion

UT

jasmin + karma


Modules

Modules are AngularJS’s way of packaging relevant code under a single name

a module define its own controllers, service, factories and directives; module can depend on other modules as dependencies; module is the one bootstrap angualrjs: main entry point - passing module name to ng-app

define module : angular.module('notesApp', []);

第二个参数是一个array - 这个module 所依赖的modules

Controller

angular.module('notesApp', [])
.controller('MainCtrl', [function() {
// Controller-specific code goes here
console.log('MainCtrl has been created');
}]);

Controller(): 第一个参数是contoller 名字,第二个参数是数组:数组最后一个是controller function, 前面是dependencies

notes: 以前用scope, angular 1.2 后controller as + this (this 最好assign给proxy variable)

eg

<html ng-app="notesApp">
<head><title>Notes App</title></head>
<body ng-controller="MainCtrl as ctrl">
{{ctrl.message}} AngularJS.

<button ng-click="ctrl.changeMessage()">
Change Message
</button>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js">
</script>
<script type="text/javascript">
angular.module('notesApp', [])
.controller('MainCtrl', [function() {
var self = this;
self.message= 'Hello ';
self.changeMessage = function() {
self.message = 'Goodbye';
};
}]);
</script>
</body>
</html>

Form

<form ng-submit="ctrl.submit1()">
<input type="text" ng-model="ctrl.username">
<input type="password" ng-model="ctrl.password">
<input type="submit" value="Submit">
</form>

// controller
angular.module('notesApp', []).controller('MainCtrl', [function() {
var self = this;
self.submit1 = function() {
// Create user object to send to the server
var user = {username: self.username, password: self.password};
console.log('First form submit with ', user);
};

}]);


valdiation

eg

<form ng-submit="ctrl.submit()" name="myForm">
<input type="text"
name="uname"
ng-model="ctrl.user.username"
required
ng-minlength="4">
<span ng-show="myForm.uname.$error.required">
This is a required field
</span>
<span ng-show="myForm.uname.$error.minlength">
Minimum length required is 4
</span>
<span ng-show="myForm.uname.$invalid">
This field is invalid
</span>
...

</form>
Form state CSS class applied
$invalid ng-invalid
$valid ng-valid
$pristine ng-pristine
$dirty ng-dirty

Other Form Controls

<textarea ng-model="ctrl.user.address" required></textarea>

<input type="checkbox" ng-model="ctrl.user.agree">

<div ng-init="user = {gender: 'female'}">
<input type="radio"
name="gender"
ng-model="user.gender"
value="male">
<input type="radio"
name="gender"
ng-model="user.gender"
value="female">
</div>

<div ng-init="location = 'India'">
<select ng-model="location">
<option value="USA">USA</option>
<option value="India">India</option>
<option value="Other">None of the above</option>
</select>
</div>

Services

AngularJS services are functions or objects that can hold behavior or state across our application.

Any service known to AngularJS (internal or our own) can be simply injected into any other service, directive, or controller by stating it as a dependency.

build-in services

AngularJS prefixes all the services that are provided by the AngularJS library with the $ sign

eg $log, $http, $window etc...


angular.module('notesApp', [])
.controller('MainCtrl', ['$log', function($log) {
var self = this;
self.logStuff = function() {
$log.log('The button was pressed');
};
}])

Creating services

  • angular.module().factory
  • factory return object contains service definition
  • service act as application-level store which can hold state

Difference between factory, service and provider

Service can use javascript class

function ItemService() {
var items = [
{id: 1, label: 'Item 0'},
{id: 2, label: 'Item 1'}
];
this.list = function() {
return items;
};
this.add = function(item) {
items.push(item);
};
}

angular.module('notesApp', []).service('ItemService', [ItemService])

Provider: can be useful when we need to set up some configuration for our service before our application loads.

$http

$http is a core AngularJS service that allows us to communicate with server endpoints using XHR.

.controller('MainCtrl', ['$http', function($http) {
var self = this;
self.items = [];
$http.get('/api/note').then(function(response) {
self.items = response.data;
}, function(errResponse) {
console.error('Error while fetching notes');
});

filter

AngularJS filters are used to process data and format values to present to the user

{{expression | filter}}

COMMON ANGULARJS FILTERS - currency - number - Lowercase/uppercase - json - etc...

filter filer: the filter filter in AngularJS is used to filter an array based on predicates or functions, and decide which elements of an array are included

Any filter, whether built-in or our own, can be injected into any service or controller by affixing the word “Filter” at the end of the name of the filter, and asking it to be injected

Eg : timeago

.filter('timeAgo', [function() {
var ONE_MINUTE = 1000 * 60;
var ONE_HOUR = ONE_MINUTE * 60;
var ONE_DAY = ONE_HOUR * 24;
var ONE_MONTH = ONE_DAY * 30;

return function(ts) {
var currentTime = new Date().getTime();
var diff = currentTime - ts;
if (diff < ONE_MINUTE) {
return 'seconds ago';
} else if (diff < ONE_HOUR) {
return 'minutes ago';
} else if (diff < ONE_DAY) {
return 'hours ago';
} else if (diff < ONE_MONTH) {
return 'days ago';
} else {
return 'months ago';
}
};
}]);

route

Any URL fragment after the # sign gets ignored by the browser in the server call.

Screen Shot 2020-11-11 at 10.38.15 PM

Angular ui-router

Screen Shot 2020-11-11 at 11.19.16 PM

$stateProvider

  1. Call $state.go(). High-level convenience method. Learn More
  2. Click a link containing the ui-sref directive. Learn More
  3. Navigate to the url associated with the state. Learn More.
$stateProvider.state('contacts', {
template: '<h1>My Contacts</h1>'
})

multi named view

<!-- index.html -->		
<body>
<div ui-view="filters"></div>
<div ui-view="tabledata"></div>
<div ui-view="graph"></div>
</body>

$stateProvider
.state('report', {
views: {
'filters': { ... templates and/or controllers ... },
'tabledata': {},
'graph': {},
}
})

Directive

Behavior modifiers + Reusable components

retrcict: A(attribute), E(Element), C(class),M(comments)

link:it defines APIs and functions that are necessary for the directive, in addition to manipulating and working with the DOM

link: function($scope, $element, $attrs) {}

scope: By default, each directive inherits its parent’s scope, which is passed to link function.

  • False: default, same as parent
  • True, inherit while create a child scope of its own
  • object: isolated scope, data need to be passed in through html attributes
  • =: specifies that the value of the attribute in HTML is to be treated as a JSON object
  • @: specifies that the value of the attribute in HTML is to be treated as a string,
  • & sign specifies that the value of the attribute in HTML is a function in some controller whose reference needs to be available to the directive

replace

If we specify it to true, AngularJS removes the element that the directive is declared on, and replaces it with the HTML template from the directive definition object

complie

directive lifecycle: complie -> link

compile step in a directive is the correct place to do any sort of HTML template manipulation and DOM transformation.


Lifecycle

Screen Shot 2020-11-12 at 9.54.05 PM

How angular detect changes and uddate UI?

Events:

  • user make modification (types in , checks a checkbox, clicks a button)
  • XHR
  • $timeout or $interval

angular add watchers for all binding and ng-model, when above events happened, angularjs check if anything changed

The digest cycle

responsible for keeping the UI up to date in an AngularJS application. T

$rootScope.$apply function to ensure AngularJS knows to redraw the UI and run a complete digest cycle as needed.

$watch

get triggered by AngularJS whenever the variable under watch changes, and we get access to both the new and the old value in such a case.

Apply Vs Digest

主要是强制更新model,一般是outside angular(三方lib,原始生s)

https://www.tutlane.com/tutorial/angularjs/angularjs-watch-digest-and-apply-functions


broadcast vs emit + rootscope

http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx

https://medium.com/@shihab1511/communication-between-controllers-in-angularjs-using-broadcast-emit-and-on-6f3ff2b0239d

$broadcast() as well as $emit() allow you to raise an event in your AngularJS application

The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite.

broadcast : 向下

emit: 向上


module dependencies

https://mobiarch.wordpress.com/2014/11/28/understanding-module-dependency-in-angularjs/

Use controller, directive and services from module dependency