AngularJS Fetch Box
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.js"></script>
<div ng-controller="MyCtrl">
<my-directive2></my-directive2>
<my-directive service-fn="myService( fetchText )" ng-model="data"></my-directive>
<pre>{{ data }}</pre>
</div>
JavaScript
var myApp = angular.module( 'myApp', [] );
myApp.controller( 'MyCtrl', [ '$scope', '$q', function ( $scope, $q ) {
$scope.myService = function( params ) {
var res = $q.defer();
res.resolve([ {foo: 1}, {foo: 2} ]);
return res.promise;
};
}]);
myApp.directive( 'myDirective2', function () {
return {
restrict: 'E',
replace: true,
template: '<div><input type="text" ng-model="fetchText"><pre>"{{fetchText}}"</pre></div>',
scope: {},
link: function link( scope, element, attrs ) {
var input = element.find( 'input' ),
ngModelCtrl = input.controller( 'ngModel' );
ngModelCtrl.$parsers.push( function ( viewValue ) {
console.log( 'input', '"' + viewValue + '"' );
return viewValue;
});
scope.$watch( 'fetchText', function () {
console.log( arguments );
});
}
};
});
myApp.directive( 'myDirective', function () {
var trimRegEx = /^\s+|\s+$/gm;
return {
restrict: 'E',
replace: true,
require: 'ngModel',
template: '<div><input type="text" ng-model="fetchText"><pre>"{{fetchText}}"</pre></div>',
scope: {
ngModel: '=',
serviceFn: '&',
autoSelectFn: '&'
},
link: function link( scope, element, attrs ) {
var input = element.find( 'input' ),
ngModelCtrl = input.controller( 'ngModel' ),
minMatchParse = parseInt( attrs.minMatch, 10 ),
minMatch = ( angular.isNumber( minMatchParse ) && !isNaN( minMatchParse ) && minMatchParse ) || 2;
scope.$on( 'cpFetchBox:clear', clearFetch );
ngModelCtrl.$parsers.push( function ( viewValue ) {
console.log( 'fetch', viewValue );
var fetchItems = [],
length;
// clearFetch will send undefined
if ( angular.isDefined( viewValue ) ) {
fetchItems = viewValue.split( ',' );
length = fetchItems.length - 1;
angular.forEach( fetchItems , function( fetchItem, i ) {
// IE 8...