Home >Web Front-end >JS Tutorial >AngularJS user selector directive example analysis
This article analyzes the AngularJS user selector directive with examples. Share it with everyone for your reference, the details are as follows:
When developing forms, we often need to use the user selector. User data is generally stored in the following way:
User 1, User 2, User 3
We Selectors can be implemented using angular directives.
<!DOCTYPE html> <html ng-app="app"> <head> <meta charset="UTF-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script src="../assets/js/angular.min.js"></script> <link rel="stylesheet" href="../assets/css/bootstrap.min.css"> <link rel="stylesheet" href="../assets/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="../assets/css/component.css"> <link rel="stylesheet" href="../assets/css/form.css"> <link rel="stylesheet" href="../assets/css/font-awesome.min.css"> <script src="../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 name="names"></div> <button ng-click="getData()">获取数据</button> </body> </html>
Template URL
<div> <span ng-repeat="item in names"> {{item}}<a class="btn btn-xs fa-remove" title="移除该项" ng-click="remove($index)"></a> </span> <a class="btn btn-sm btn-primary fa-search" ng-click="selectUser()">选择</a> </div>
In the command, an independent scope is used. The incoming data is a comma-delimited string, and we use an array for operation.
The trick here is to convert between strings and arrays.
A command-independent scope is used here, and watch is used to operate the array. It should be noted that if you monitor the array, you need to use in-depth monitoring.