我制作了内部使用Angular UI打字指令的自定义指令,但无法按预期工作。在我的指示模型中,未更新选择。有人帮助吗?用于测试,我使用静态数组而不是HTTP服务。plunker在这里。
.directive('httpDictionary', ['$compile', function($compile){
return {
scope: {
},
restrict: 'A',
controllerAs: "dm",
controller: ['$scope', '$http', 'ARRAY', function($scope, $http, ARRAY){
var dm = this;
dm.dict = function(val){
return ARRAY; // for testing only
// return $http.get($scope.dictionaryUrl, { ...
}
}],
link: function(scope, element, attributes, ngModel) {
scope.dictionaryUrl = attributes.httpDictionary;
element.removeAttr('http-dictionary'); // avoid loop
element.attr('uib-typeahead', 'd for d in dm.dict($viewValue)');
$compile(element)(scope);
}
};
}])
为了帮助绑定到模型,我通常使用uib-typeahead
设置typeahead-on-select
。这样,您可以在设置新模型时检查或执行一些其他代码。
我在这里找到了一个plunker,但进行了一些小调整:
-
我将输入文本字段隔离到其自己的视图中,以便将功能与父视图分开。
-
我将
test
模型传递给了指令的范围属性,然后将其绑定到指令控制器(使用bindToController
属性),因此,如果您需要test
模型来将来与父级控制器通信,则可以执行所以。
希望这会有所帮助。
我做了下面的作品。plunker代码在这里。我在指令范围中绑定了ngmodel,并使用了typeahead-on-select
回调功能。我不认为这是优雅的,但是可以起作用。我一直在考虑使用$watch
,但没有成功。如果您有更好的灵魂,我会很高兴的。
.directive('httpDictionary', ['$compile', function($compile){
return {
scope: {
ngModel: '='
},
restrict: 'A',
controllerAs: "dm",
controller: ['$scope', '$http', 'ARRAY', function($scope, $http, ARRAY){
var dm = this;
dm.dict = function(val){
return ARRAY; // for testing only
// return $http.get($scope.dictionaryUrl, { ...
}
dm.select = function($model) {
$scope.ngModel = $model;
}
}],
link: function(scope, element, attributes, ngModel) {
scope.dictionaryUrl = attributes.httpDictionary;
element.removeAttr('http-dictionary'); // avoid loop
element.attr('uib-typeahead', 'd for d in dm.dict($viewValue)');
element.attr('typeahead-on-select','dm.select($model)');
element = $compile(element)(scope);
}
};
}])