Home > Web Front-end > JS Tutorial > body text

Angular updates directive_AngularJS based on the status of the service

WBOY
Release: 2016-05-16 15:06:38
Original
1094 people have browsed it

Angular JS (Angular.JS) is a set of frameworks, templates, data binding and rich UI components used to develop web pages. It supports the entire development process and provides the architecture of web applications without manual DOM manipulation.

AngularJS is designed to overcome the shortcomings of HTML in building applications. HTML is a good declarative language designed for static text display, but it is weak when it comes to building WEB applications. AngularJS comes into being here, making up for the natural shortcomings of HTML and used to build web applications.

TL;DR

This article explains three methods of updating directives based on the status of the service. They are $watch expressions, event delivery, and controller computed properties.

Question

I have a readerService which contains some status information (such as connection status and battery). Now I need to make a directive to display these states. Because it only needs to get data from readerService and does not require any external values, I directly inject the service into it. But how to update becomes a problem.

The code of service is as follows.

const STATUS = {
DETACH: 'DETACH',
ATTACH: 'ATTACH',
READY: 'READY'
}
class ReaderService {
constructor() {
this.STATUS = STATUS
// The status will be changed by some callbacks
this.status = STATUS.DETACH
}
}
angular.module('app').service('readerService', readerService)
Copy after login

directive code is as follows:

angular.module('app').directive('readerIndicator', (readerService) => {
const STATUS = readerService.STATUS
const STATUS_DISPLAY = {
[STATUS.DETACH]: 'Disconnected',
[STATUS.ATTACH]: 'Connecting...',
[STATUS.READY]: 'Connected',
}
return {
restrict: 'E',
scope: {},
template: `
<div class="status">
{{statusDisplay}}
</div>
`,
link(scope) {
// Set and change scope.statusDisplay here
}
}
})
Copy after login

I have tried the following methods, which are introduced one by one below.

Method 1: $watch

The first method that comes to mind is to use $watch in the directive to monitor readerService.status. Since it's not an attribute of the directive scope, we need to wrap it in a function. Angular will calculate and compare the old and new values ​​during dirty-checking, and the callback will be triggered only if the state actually changes.

// In directive
link(scope) {
scope.$watch(() => readerService.status, (status) => {
scope.statusDisplay = STATUS_DISPLAY[status]
})
}
Copy after login

This method is simple and efficient enough. As long as the code involving changes in readerService.status triggers dirty-checking, the directive will be automatically updated. service does not require any code modification.

But if there are multiple directive attributes that are affected by service status, then the $watch code will be more obscure. Especially when the value modified by $watch will affect other values. For example:

// In directive
link(scope) {
scope.$watch(() => readerService.status, (status) => {
scope.statusDisplay = STATUS_DISPLAY[status]
scope.showBattery = status !== STATUS.DETACH
})
scope.$watch('showBattery', () => {
// some other things depend on showBattery
})
}
Copy after login

At this time, declarative programming style will be easier to understand, such as computed property in Ember or Vue. This will be discussed later.

Method 2: $broadcast/$emit + $on

The idea is that the service sends an event every time the state changes, and then the directive listens to the event to change the state. Because the status may have been updated when the directive is rendered. So we need to calculate an initial value in link.

I first did it with $broadcast. The code is as follows:

// In service
setStatus(value) {
this.status = value
// Need to inject $rootScope
this.$rootScope.$broadcast('reader.statusChanged', this.status)
}
// In directive
link(scope) {
scope.statusDisplay = STATUS_DISPLAY[nfcReaderService.status]
scope.$on('reader.statusChanged', (event, status) => {
scope.statusDisplay = STATUS_DISPLAY[status]
})
}
Copy after login

But I immediately discovered that the UI update after $broadcast always takes more than 1 second (but the $on callback is very fast). After some Google research, we found out that the reason is that $broadcast broadcasts to all lower-level scopes, and then dirty-checking is done after the broadcast is completed. A better approach is to use $emit, which will only pass events upward, but you must use $rootScope to send events or listen for events.

The modified code is as follows:

// In service
setStatus(value) {
this.status = value
// Use $emit instead of $broadcast
this.$rootScope.$emit('reader.statusChanged', this.status)
}
// In directive
link(scope) {
scope.statusDisplay = STATUS_DISPLAY[nfcReaderService.status]
// Use $rootScope instead of scope
$rootScope.$on('reader.statusChanged', (event, status) => {
scope.statusDisplay = STATUS_DISPLAY[status]
})
}
Copy after login

If you have to use $broadcast for some reason, you can use $digest or $apply at the end of the $on callback to force trigger dirty-checking, which can also achieve the purpose of quickly updating the UI.

Method 3: controller + property

I personally think the first two methods can solve the problem, but the code maintainability is not very good. $watch is very difficult to understand when attributes are related to each other. $emit/$on requires writing some logic twice (when initializing the directive and when the callback is executed). In Method 1, I mentioned that sometimes declarative attributes are easier to understand than $watch. This method is to use controller. The directive can set its own controller as the data source (or view model), and we can use the properties that need to be calculated as the properties of the controller. This way they will be automatically calculated during dirty-checking.

// In directive
class ReaderController {
constructor($scope, readerService) {
this.readerService = readerService
}
get statusDisplay() {
return STATUS_DISPLAY[this.readerService.status]
}
}
return {
// ...
controller: ReaderController,
controllerAs: 'vm',
template: `
<div class="status">
{{vm.statusDisplay}}
</div>
}
Copy after login

In this way, most of the logic can be moved to the controller. If there is no DOM operation, we don't even need to write the link method. There is no need to add additional $watch and $on . Just because of the characteristics of dirty-checking, properties bound to template are often calculated several times more. So the properties must be very simple. In most cases this won't be a problem.

The above content is the Angular update directive based on the status of the service introduced by the editor. I hope it will be helpful to everyone!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template