gpt4 book ai didi

javascript - 将 Service 注入(inject) Directive AngularJS 和数据绑定(bind)中。

转载 作者:行者123 更新时间:2023-12-03 07:41:36 25 4
gpt4 key购买 nike

我创建了一个通过 $http 获取数据的服务,该数据存储在该服务的变量中,我还创建了一个指令,使用该服务创建带有选项的标签选择,这些选项是在服务中获取的,但这是我的问题,获得的数据从未与指令连接。

服务和指令:

angular.module('myModule'[])
.factory('myService', ['$http', function($http){
var listOptions = [];
$http({
method: 'GET',
url: 'urlToDataJson'
}).then(function(resp){
listOptions = resp.data
})
;
return {
list: listOptions;
}
}]
.directive('myDirective', ['myService', function(myService){
restrict: 'E',
template: '<select ng-options="item.id as item.name for item in list"></select>',
replace: true,
controller: ['$scope', function($scope)
$scope.list = MyService.list;
]
}])
;

使用 Chrome 的 DevTool,我可以看到 $http 运行后数据已更新,但数据未显示在选项中。

上面的代码是我需要做的一个例子。

最佳答案

您的 $http 调用返回一个 Promise 对象。将 $http 调用包装在函数中并返回 Promise 对象,然后在您的指令中调用此函数并解析 Promise 对象并获取数据。

具体来说,

getData(){
return $http({
method: 'GET',
url: 'urlToDataJson'
}).then(function(resp){
listOptions = resp.data
); // this returns a promise
}

然后在您的指令中,像这样解决 promise :

MyService.getData().then(function(data){
console.log(data); // <-- this is how you access the result of your $http call
});

关于javascript - 将 Service 注入(inject) Directive AngularJS 和数据绑定(bind)中。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35388232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com