1
我想創建一個Angular 1.6組件,它是輸入標籤的包裝。我正在創建一個類型提前或自動完成。我必須在html中使用ng-model來創建組件,這很好,但我希望在子輸入元素中使用ng-model。對於一個組件,你必須使用一個元素,並且不能使用屬性標籤,如指令使用。我已經創建了一個代碼筆來說明我正在嘗試做什麼。如何將ng-model從Angular 1.6組件傳遞到輸入元素
我想用ngController更新輸入元素的值。在代碼筆中,如果您輸入了輸入內容,則會在輸入元素下方看到綁定的模型數據。
下面是代碼:
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>