【发布时间】:2017-04-05 03:56:10
【问题描述】:
我正在尝试创建一个 Angular 1.6 组件,它是输入标签的包装器。我正在创建一个提前或自动完成的类型。我必须在 html 中使用 ng-model 来创建组件,这很好,但我希望在子输入元素中使用 ng-model。对于组件,您必须使用元素,并且不能使用指令使用的属性标记。我创建了一个代码笔来说明我想要做什么。
我想使用 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>
【问题讨论】:
标签: javascript angularjs custom-component