Home >Web Front-end >JS Tutorial >A brief discussion on the 4 design patterns in angular instructions
This article will introduce to you the 4 design patterns in the angular directive. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
[Related recommendation: "angular tutorial"]
The function set of the directive is very rich, but we have discovered the Pareto distribution: A large number of instructions written in Angular will only use a small proportion of usability and design patterns. These instructions can be roughly divided into 4 categories:
These directives follow a simple design pattern: they will watch variables and update DOM elements to reflect changes in variables such as ngClass ,ngBind.
angular.module('app', []). directive('myBackgroundImage', function () { return function (scope, element, attrs) { scope.$watch(attrs.myBackgroundImage, function (newVal, oldVal) { element.css('background-image', 'url(' + ')'); }); } });
At a high level, event handler directives can bind DOM events with data bindings by calling the $apply function. Such as ngClick, the following similar custom click.
angular.module('app', []). directive('myNgClick', function () { return function (scope, element, attrs) { element.click(function () { scope.$eval(attrs.myNgClick); scope.$apply(); }); } });
This mode uses both the render-only directive and the event handler mode to create directives that control the state of variables.
angular.module('app', []). directive('myNgClick', function () { return function (scope, element, attrs) { //监视和更新 scope.$watch(attrs.toggleButton, function (v) { element.val(!v ? 'Disable' : 'Enable'); }); //事件处理程序 element.click(function () { scope[attrs.toggleButton] = !scope[attrs.toggleButton]; scope.$apply(); }); } });
Template instructions can construct powerful instructions by setting template options. In fact, the function returned by the above example is equivalent to the link function of the template. .
angular.module('app', []). directive('imageCarousel', function () { return { templateUrl: 'view/index.html', controller: carouselController, scope: {}, link: function (scope, element, attrs) { scope.$parent.$watch(attrs.imageCarousel, function (v){ scope.images = v; }); } } });
There are many other options for template options. Please refer to my other blog posts. The main focus here is design patterns.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of A brief discussion on the 4 design patterns in angular instructions. For more information, please follow other related articles on the PHP Chinese website!