我的应用有两个字段:客户端和服务(参与)。我为客户端添加了自动完成功能(使用此解决方案https://stackoverflow.com/a/19547431/223934)。我想更进一步:如果我选择了一个客户端,它将为该客户端发送可用服务请求(约定),并在视图中显示为选项。
CSM.controller('myController', ['$scope', '$http', function ($scope, $http) {
$scope.availableEngagements = '';
....
和指令
CSM.directive("autocomplete", ["AutoCompleteService", function (AutoCompleteService) {
return {
restrict: "A",
scope: {
action: '@',
availableEngagements: "="
},
link: function (scope, elem, iAttrs, ctrl, http) {
iAttrs.$observe('action', function (actionValue) {
elem.autocomplete({
source: function (searchTerm, response, scope) {
AutoCompleteService.search(searchTerm.term, actionValue).then(function (autocompleteResults) {
response($.map(autocompleteResults, function (autocompleteResult) {
return {
label: autocompleteResult.name,
value: autocompleteResult.id,
desc: autocompleteResult.name
};
}));
});
},
minLength: 1,
select: function (event, selectedItem) {
// Do something with the selected item, e.g.
scope.selectedValue = selectedItem.item.value;
scope.$apply();
if (actionValue === "client") {
scope.availableEngagements = AutoCompleteService.engagementSearch(selectedItem.item.value);
//scope.$apply();
}
event.preventDefault();
}
});
});
}
};
}]);
CSM.factory("AutoCompleteService", ['$http', function ($http) {
return {
search: function (term, action) {
return $http.post("autocomplete/" + action + "/", {term: term}).then(function (response) {
return response.data;
});
},
engagementSearch: function (client) {
//Tai sao POST ko duoc ma GET lai duoc?
$http.get("autocomplete/engagement/?term=" + client).success(function (data) {
return data;
});
}
};
}]);
我尝试在this guide中应用绑定方法“=”。自动完成工作正常,应用程序成功发送请求并接收服务(约定)的结果。它只是没有传递到全局范围以在视图中显示。
请帮我指出我的代码有什么问题。非常感谢你。
答案 0 :(得分:2)
首先要注意的是,你的指令创建了一个隔离范围,它是父范围的子范围(不是原型继承的)。因此,在指令中使用$parent
来更新控制器上定义的作用域对象:
scope.$parent.availableEngagements = AutoCompleteService.engagementSearch(selectedItem.item.value);