반응형
Angular에서 링크 기능을 실행하기 전에 컨트롤러에서 데이터를 기다립니다.JS 지시어
링크 기능이 실행되기 전에 컨트롤러로부터의 데이터가 명령어로 로드되었는지 확인하려면 어떻게 해야 합니까?
psuedo 코드를 사용하여 다음을 수행할 수 있습니다.
<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
사실로 해결되다
<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
}
)
})
또는 약속을 사용합니다.
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)
});
}
}
app.directive('MyDirective', function() {
return {
controller: function() {
this.$postLink = function() {
// here will run after the link function,
// and also after the binding came in
};
},
controllerAs: 'vm'
};
});
각도 1.5 컴포넌트의 라이프 사이클이 명확하게 정의되어 있으며, 이 컴포넌트는 다음과 같은 지침에 따라 작동합니다.
언급URL : https://stackoverflow.com/questions/27485990/wait-for-data-in-controller-before-link-function-is-run-in-angularjs-directive
반응형
'programing' 카테고리의 다른 글
JSON에서 커스텀 Json Converter를 구현하는 방법.인터넷? (0) | 2023.03.13 |
---|---|
왜 앵글은JS 문서는 모델 지시문에 점을 사용합니까? (0) | 2023.03.13 |
ng-click과 ng-click의 차이점 (0) | 2023.03.13 |
HTML의 여러 클래스 속성 (0) | 2023.03.13 |
리액션 네이티브 스타일. 폭: 백분율 - 숫자 (0) | 2023.03.13 |