AngularJS用户选择器指令实例分析

在开发表单时,我们需要使用经常需要使用到用户选择器,用户的数据一般使用如下方式存储:

用户1,用户2,用户3

我们可以使用angular指令实现选择器。

<!DOCTYPE html> <html ng-app="app"> <head> <meta charset="UTF-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script src="https://www.jb51.net/assets/js/angular.min.js"></script> <link href="https://www.jb51.net/assets/css/bootstrap.min.css"> <link href="https://www.jb51.net/assets/css/bootstrap-theme.min.css"> <link href="https://www.jb51.net/assets/css/component.css"> <link href="https://www.jb51.net/assets/css/form.css"> <link href="https://www.jb51.net/assets/css/font-awesome.min.css"> <script src="https://www.jb51.net/assets/js/angular.min.js"></script> <script type="text/javascript"> var base=angular.module("directive",[]); base.directive('htSelector', function() { return { restrict : 'AE', templateUrl:'selector.html', scope: { name: '=name' }, link: function(scope, element, attrs) { var aryName=scope.name.split(","); scope.names=aryName; scope.remove=function(i){ aryName.splice(i,1); }; scope.$watch( "names", function (newValue,oldValue) { if(newValue!=oldValue){ scope.name=aryName.join(","); } },true ); scope.selectUser=function(){ aryName.length = 0; aryName.push("韩信"); } } } }); var app=angular.module("app",["directive"]); app.controller('ctrl', ['$scope',function($scope){ $scope.names='自由港,马云,刘强东'; $scope.getData=function(){ console.info($scope.names) } }]) </script> </head> <body ng-controller="ctrl"> <div ht-selector></div> <button ng-click="getData()">获取数据</button> </body> </html>

模版URL

<div> <span ng-repeat="item in names"> {{item}}<a title="移除该项" ng-click="remove($index)"></a> </span> <a ng-click="selectUser()">选择</a> </div>

在指令中,使用了独立的scope,传入的数据为使用逗号分割的字符串,我们使用了数组进行操作。

这里的技巧是在字符串和数组之间进行转换。

这里使用了指令独立的scope,使用了watch 对数组进行操作,需要注意的是如果监控数组,需要使用深度监控。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzgzsw.html