I am trying to create an Angular 1.6 component that is a wrapper for an input tag. I am creating a type ahead or autocomplete. I have to use ng-model in the html to create the component and that is fine, but I want that ng-model used in the child input element. With a component you have to use an element and can't use attribute tag like directives use. I have created a code pen to illustrate what I am trying to do.
I want to use ngController to update the value in the input element. In the code pen, if you type in the input, you will see the bound model data show up below the input element.
Here is the code:
angular.module('app', ['EntryField']);
angular.module('app').controller('DataController', ['$scope', function($scope) {
$scope.fieldDataArray = [{"label": "First Name", "content": ""}, {"label": "Last Name", "content": ""}];
console.log("$scope.fieldDataArray: ", $scope.fieldDataArray)
}]);
angular.module('EntryField', []).component('customAutoComplete', {
template: '<input type="text" name="input" ng-model="$ctrl.ngModelController.$modelValue" autocomplete="off"/><br>[{{$ctrl.ngModelController.$viewValue}}]',
require: {
ngModelController: "ngModel"
},
bindings: {},
controller: 'CustomAutocompleteController'
});
angular.module('EntryField').controller('CustomAutocompleteController', CustomAutoController);
CustomAutoController.$inject = ['$scope', '$element'];
function CustomAutoController($scope, $element) {
let ctrl = this;
ctrl.$onInit = function() {
ctrl.ngModelController.$parsers.unshift(function (inputValue) {
handleInputUpdate(inputValue);
});
}
function handleInputUpdate(inputValue) {
//Do autocomplete functionality
}
}
<html ng-app="app">
<head></head>
<body>
<div>Angular 1.x Auto Complete</div>
<div ng-controller="DataController">
<div ng-repeat="fieldData in fieldDataArray">
<div>{{fieldData.label}}</div>
<custom-auto-complete ng-model="fieldData.content"></custom-auto-complete>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
</body>
</html>