How can I call some directive from Controller after success ajax request?
For example if I have function:
function successAjax()
{
call directive
}
and if I have in template:
<directive></directive>
there should appear:
<p>success</p>
How can I call some directive from Controller after success ajax request?
For example if I have function:
function successAjax()
{
call directive
}
and if I have in template:
<directive></directive>
there should appear:
<p>success</p>
You have a few choices to go the way you want. If I were you, I would instead move your AJAX call into your directive to sidestep the issue entirely (even better: move the AJAX call to a service that gets injected into the directive):
angular.module('app').directive('directive', [
'$http',
function($http) {
return {
link: link,
scope: {}
};
function link(scope, elem, attrs) {
scope.doAjax = doAjax;
function doAjax() {
$http.get('url').then(function() {
elem.append('<p>success</p>');
});
}
}
}
]);
If you absolutely have to have the AJAX call in your controller, you can use events, but you should be sparing with these as they will clog up the digest loop:
// Controller
function doAjax() {
$http.get('url').then(function() {
$scope.$broadcast('some.event.descriptor');
});
}
// Directive
function link(scope, elem, attrs) {
scope.$on('some.event.descriptor', function() {
elem.append('<p>success</p>');
});
}
Another option you have is to bind some data from the controller to your directive:
// Controller
$scope.someData = '';
$http.get('url').then(function() {
$scope.someData = 'success';
});
<!-- Controller Template -->
<directive data-something="someData"></directive>
// Directive
function() {
return {
scope: {
something: '='
}
};
}
<!-- Directive Template -->
<p>{{ something }}</p>
First i don't feel any need of showing success message after ajax call using directive. Angularjs has used $q service to deal with http calls and return promise object and handle that in your controller, after that you can bind the success message to your view from controller scope.
If you want to trigger directive from controller your can use $broadcast to send event to entire $rootScope and handle that in your directive.
Example:
$rootScope.$broadcast('myFunction',{});
In Directive:
scope.$on('myFunction',function(event, data){
// Do what ever you want to do
});
This would be hopefully help you. Thanks.
$rootScope. this is fine only if you have some listeners spreaded over the app.