Reputation: 2224
I have an async function that retrieves data from the server, and I have a directive that is supposed to display the data of whatever that async function retrieves.
What I am trying to do is to place an ng-show in false in my directive, supposing that the directive will not load unless I place the ng-show in true. The ng-show would remain false until my async function retrieves the data.
The thing is this is not working, the directive would load regardless of if I place an ng-show or not on it - any other ideas?
This is what I have tried in code :
Js :
getFile.then(function (result) {
$scope.show = true;
Utilities.safeApply($scope);
})
Html :
section class="list file-list group" ng-show="show" view-mode="assets">
<file file="model.file"></file>
</section>
Directive :
.directive('file', ['$rootScope', '$compile', function($rootScope, $compile) {
return {
restrict: 'E',
replace: true,
templateUrl: 'file.html',
scope: {
show: '='
},
controller: function($scope) {
//do stuff here once async function finished
}
Upvotes: 0
Views: 172
Reputation: 2526
ngShow and ngHide merely show and hide content, they don't conditionally add it or remove it from the page. If you really want that behavior, look into ngIf.
However, I think your problem would be better solved setting up a watcher in your directive that acts when the content is ready. This is a "more angular" way of approaching the problem, since it relies on data-binding.
.directive('file', ['$rootScope', '$compile', function($rootScope, $compile) {
return {
restrict: 'E',
replace: true,
templateUrl: 'file.html',
scope: {
file: '=', // YOU DIDN'T HAVE THIS YET
},
controller: function($scope) {
$scope.$watch('file', function (newValue) {
if (!newValue) { return; }
// do async code here. $scope.file will be defined
};
}
As the other poster mentioned, you may have to call $scope.$apply() to fire a digest cycle after receiving the result of your Ajax call. It depends on the what your getFile
method looks like. If it uses one of Angular's core services, like $http, you probably won't need to manually mess with the digest cycles.
Upvotes: 1
Reputation: 2603
Have you tried calling $scope.$apply() at the end of (or after) your function? This works for me in similar situations. I think it has something to do with updating the $scope from outside of angular.
Disclaimer: I don't know if this is good practice, but I've been forced to use it a few times working with async functions and it does what I want it to do
Upvotes: 0