angularJS操作input元素程式碼例項

admin發表於2017-04-12

本章節分享一段angularJS中input指令的一段程式碼例項。

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title> 
</head>
<script src="js/jquery.js">
</script>
<script src="js/angular.min.js">
</script>
<body ng-app="Demo">
<div ng-controller="TestCtrl">
  <input type="text" ng-model="a" test />
  <button ng-click="show(a)">檢視</button>
</div>
</body>
<script>
var app = angular.module('Demo', [], angular.noop);
app.directive('test', function(){
  //input 指令的 link有第四個引數,$ctrl有些方法,你可以自己拿來用
  var link = function($scope, $element, $attrs, $ctrl){
    console.log( $ctrl )
    $ctrl.$formatters.push(function(value){
      return value.join(',');
    });
    $ctrl.$parsers.push(function(value){
      return value.split(',');
    });
  }
  return {compile: function(){return link},
    require: 'ngModel',
    restrict: 'A'}
  });
  app.controller('TestCtrl', function($scope){
    $scope.a = [];
    //$scope.a = [1,2,3];
    $scope.show = function(v){
      console.log(v);
    }
});
</script>
</html>

相關文章