首页 > 语言 > JavaScript > 正文

Angularjs 创建可复用组件实例代码

2024-05-06 15:08:43
字体:
来源:转载
供稿:网友

AngularJS框架可以用Service和Directive降低开发复杂性。这个特性非常适合用于分离代码,创建可测试组件,然后将它们变成可重用组件。

Directive是一组独立的JavaScript、HTML和CSS,它们封装了一个特定的行为,它将成为将来创建的Web组件的组成部分,我们可以在各种应用中重用这些组件。在创建之后,我们可以直接通过一个HTML标签、自定义属性或CSS类、甚至可以是HTML注释,来执行一个Directive。

这一篇教程将介绍如何创建一个‘自定义步长选择' Directive,它可以作为一个可重用输入组件。本文不仅会介绍Directive的一般创建过程,还会介绍输入控件验证方法,以及如何使用ngModelController无缝整合任意表单,从而利用AngularJS表单的现有强大功能。

直接上代码:

html:

<!-- lang: html --><body ng-app="demo" ng-controller="DemoController">  <form name="form" >    Model value : <input type="text" size="3" ng-model="rating"><br>    Min value: <input type="text" size="3" ng-model="minRating"><br>    Max value: <input type="text" size="3"ng-model="maxRating"><br>    Form has been modified : {{ form.$dirty }}<br>    Form is valid : {{ form.$valid }}    <hr><divmin="minRating"max="maxRating"ng-model="rating"rn-stepper></div></form></body>

js:

<!-- lang: js -->angular.module(‘demo‘, [  ‘revolunet.stepper‘]).controller(‘DemoController‘, function($scope) {  $scope.rating = 42;     $scope.minRating = 40;  $scope.maxRating = 50;});

rn-stepper最简结构

<!-- lang: js -->// we declare a module name for our projet, and its dependencies (none)angular.module(‘revolunet.stepper‘, [])// declare our naïve directive.directive(‘rnStepper‘, function() {  return {    // can be used as attribute or element    restrict: ‘AE‘,    // which markup this directive generates    template: ‘<button>-</button>‘ +            ‘<div>0</div>‘ +            ‘<button>+</button>‘  };});

现在directive rnStepper 已经有了一个简单的雏形了。

可以有如下两种试用方法:

<div rn-stepper> </div>
<rn-stepper> </rn-stepper>

demo: http://jsfiddle.net/revolunet/n4JHg/

添加内部动作

直接上代码:

<!-- lang: js -->.directive(‘rnStepper‘, function() {  return {    restrict: ‘AE‘,    // declare the directive scope as private (and empty)    scope: {},    // add behaviour to our buttons and use a variable value    template:        ‘<button ng-click="decrement()">-</button>‘ +        ‘<div>{{value}}</div>‘ +        ‘<button ng-click="increment()">+</button>‘,    // this function is called on each rn-stepper instance initialisation    // we just declare what we need in the above template    link: function(scope, iElement, iAttrs) {      scope.value = 0;      scope.increment = function() {        scope.value++;      };      scope.decrement = function() {        scope.value--;      };    }  };});            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选