saf saf - 6 months ago 30
AngularJS Question

Angularjs run directive after success of $http

I am making a nav using custom

directive
and when some add/remove anything from that nav I wanted to reflect changes on that nav . If that nav comes from scope then I can update scope but as nav comes from directive so I don't know how to call that directive on
$http
success.

Here is my directive :

<nav_toolbar uuid=\"pk\" my-method=\"get_navs\"></nav_toolbar>


Here you can see I am using some attributes too in directive which helps me to fetch exact nav options.

Directive code :

app.directive('synapseToolbar', function() {
var controller = ['$scope', '$element', '$attrs', '$http', '$compile','Scopes',
function ($scope, $element, $attrs, $http, $compile, Scopes) {
var uuid = $scope.uuid
// my $http request comes here
// on $http success i'll set this below scope
$scope.synapse_toolbar_icons = a object
}];
return {
restrict: 'EA',
scope: {
uuid: '=',
method: '&myMethod',
},
controller: controller,
link: function (scope, element, attrs) {
var click_fn = scope.method();
$(element).click(function(e, rowid) {
click_fn(scope.link_source, scope.link_fact_type);
});
},
template: '<div ng-show="synapse_toolbar_icons" ng-repeat="toolbar in synapse_toolbar_icons" class="tile iconSizeClass synapse-toolbar bg-crimson ng-scope" data-toggle="tooltip" ng-click="bindData(toolbar.link_source, toolbar.link_fact_type)">'+
'<div dynamic="toolbar.icon_html"></div>'+
'</div>',
};
});


Function on which I want to call directive again

$scope.remove_synapse_link = function(){

$http({
method : 'POST',
}).success(function(data,status){
// here I want to call that directive again
})
.error(function(data,status){
$.notify("Something went wrong while adding dislike", "error");
});
}


Plunker http://plnkr.co/edit/FpzGkIpBPfOnoFrwQkmj?p=preview

Answer

$http returns a promise and is asynchronous. Your directive runs when your html renders. So what you do is don't render the HTML until you have the response.

HTML:

<div ng-if="ready"> 
   <div my-custom-directive></div>
</div>

Controller:

$scope.ready = false;    
$http.get('/my-request').success(function(){
    $scope.ready = true;
});

This works because the ng-if directive will create the element only if the expression becomes true.