gpt4 book ai didi

angularjs - 在 AngularJS 指令中运行链接函数之前等待 Controller 中的数据

转载 作者:行者123 更新时间:2023-12-02 21:56:58 25 4
gpt4 key购买 nike

如何确保在运行链接函数之前 Controller 中的数据已加载到指令中?

使用伪代码,我可以:

<my-map id="map-canvas" class="map-canvas"></my-map>

对于我的 html。

在我的指令中,我可能有这样的内容:

app.directive('myMap', [function() {



return{
restrict: 'AE',
template: '<div></div>',
replace: true,
controller: function ($scope, PathService) {

$scope.paths = [];

PathService.getPaths().then(function(data){
$scope.paths = data;

});

},
link: function(scope, element, attrs){
console.log($scope.paths.length);

}

}


}]);

上面的方法不起作用,因为 console.log($scope.paths.length);将在服务返回任何数据之前被调用。

我知道我可以从链接函数调用服务,但想知道是否有办法在触发链接函数之前“等待”服务调用。

最佳答案

最简单的解决方案是使用 ng-if,因为只有当 ng-if 解析为 true 时才会呈现元素和指令

<my-map id="map-canvas" class="map-canvas" ng-if="dataHasLoaded"></my-map>

app.controller('MyCtrl', function($scope, service){
$scope.dataHasLoaded = false;

service.loadData().then(
function (data) {
//doSomethingAmazing
$scope.dataHasLoaded = true
}
)
})

或者使用 promise

return {
restrict: 'AE',
template: '<div></div>',
replace: true,
controller: function ($scope, PathService) {
$scope.paths = [];
$scope.servicePromise = PathService.getPaths()
},
link: function (scope, element, attrs) {
scope.servicePromise.then(function (data) {
scope.paths = data;
console.log(scope.paths)
});
}
}

关于angularjs - 在 AngularJS 指令中运行链接函数之前等待 Controller 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27485990/

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