How to call another directive from directive angularjs - javascript

I want to call alertForm directive in loginForm directive. Where I want call 'alertForm' directive in 'loginForm' is highlighted as //i want to call here
alertForm directive
angular.module('myApp')
.directive('alertForm', function () {
return {
templateUrl: 'app/directives/alert/alertForm.html',
restrict: 'E',
scope: {
topic: '=topic',
description: '=description'
},
controller: function($scope) {
$scope.words = [];
this.showAlert = function() {
$scope.description.push("hello");
};
}
};
});
loginForm directive
angular.module('myApp')
.directive('loginForm', function() {
return {
templateUrl: 'app/directives/loginForm/loginForm.html',
restrict: 'E',
scope: {
successCallback: '&',
errorCallback: '&',
emailField: '='
},
link: function (scope, element, attrs) {
},
controller: function ($rootScope, $scope, authenticationService) {
$scope.loginFormData = {};
$scope.inProgress = false;
$scope.onLogin = function (form) {
if (form.$valid) {
$scope.inProgress = true;
authenticationService.loginUser('password', $scope.loginFormData).then(function () {
$scope.successCallback({formData: $scope.loginFormData});
}, function (err) {
$scope.inProgress = false;
if (err.message) {
**// i want to call here**
}
});
}
}
}
};
});

You can use require config of directive.
When a directive requires a controller, it receives that controller as
the fourth argument of its link function. Ref : Documentation
You can implement this in your code
angular.module(‘myApp')
.directive('loginForm', function() {
return {
templateUrl: 'app/directives/loginForm/loginForm.html',
restrict: 'E',
require:'alertForm',
scope: {
successCallback: '&',
errorCallback: '&',
emailField: '='
},
link: function (scope, element, attrs, alertFormCtrl) {
scope.alertFormCtrl = alertFormCtrl;
},
controller: function ($rootScope, $scope, authenticationService) {
$scope.loginFormData = {};
$scope.inProgress = false;
$scope.onLogin = function (form) {
if (form.$valid) {
$scope.inProgress = true;
authenticationService.loginUser('password', $scope.loginFormData).then(function () {
$scope.successCallback({formData: $scope.loginFormData});
}, function (err) {
$scope.inProgress = false;
if (err.message) {
// Calling showAlert function of alertFormCtrl
$scope.alertFormCtrl.showAlert();
}
});
}
}
}
};
});

Add the following line in the app/directives/loginForm/loginForm.html :
<alertForm topic="something" description = "something" ng-if="showAlert"></alertForm>
Now inside the loginForm directive's controller : // i want to call here
use
$scope.showAlert = true;
Note: you can use some variable to setup the topic and description as well inside the alertForm.

Related

AngularJS directive that will look at the value of my ngModel then fire off a function in the controller and be available immediately in view

I am trying to use a $scope.quickText(data) function in my controller. The function reviews the parameter 'data' and looks for any codes (ie: .smoke) and then adds that text to the value of the model.
For instance, if the ngModel value was "Completed smoke assessment" and someone types into the 'textarea' or 'text' input .smoke, it would add "patient smokes. Completed smoke assessment". This would be available to see in the view instantly as the user is typing .smoke. The function works but my directive does not.
myApp.directive('gmaEvalQuickText1', ['$timeout', function ($timeout) {
'use strict';
return {
restrict: 'A',
require: 'ngModel',
scope: {
quickTextEvaluate: '&',
},
bindToController: true,
controller: 'gmaController',
controllerAs: 'gc',
link: function ($elem, $ctrl,controller) {
$elem.on('input keyup change', function () {
var val = $elem.val().toString();
var newVal = gc.quickText(val).toString();
$ctrl.$setViewValue(newVal);
$timeout(function () {
$ctrl.$render();
});
});
}
}
}]);
I am very new to AngularJS so I am sure I am doing something wrong.
I figured out how to make it work :)
For those who need the answer:
Directive:
myApp.directive('evalQuickText', ['$timeout', function ($timeout) {
'use strict';
return {
restrict: 'A',
require: 'ngModel',
scope: {
quicktextevalfct: '='
},
link: function ($scope, $elem, attrs, $ctrl) {
$elem.on("keydown keypress", function (event) {
if(event.which === 13) {
var val = $elem.val().toString();
var newVal = $scope.quicktextevalfct(val);
$ctrl.$setViewValue(newVal + "\n");
$timeout(function () {
$ctrl.$render();
});
event.preventDefault();
}
if(event.which === 9) {
var val = $elem.val().toString();
var newVal = $scope.quicktextevalfct(val);
$ctrl.$setViewValue(newVal);
$timeout(function () {
$ctrl.$render();
});
event.preventDefault();
}
});
}
};
}]);
HTML:
eval-quick-text quicktextevalfct="quickTextEvaluate"

How to call a controller function inside AngularJS directive

Controller in page :
(function () {
'use strict';
angular.module('LVS').controller('LVSCtrl', LVSCtrl);
function LVSCtrl($scope) {
$scope.OnChange = function() {
// do
}
}
})();
This is my directive code
My Directive code :
(function () {
'use strict';
angular.module('LVS')
.directive('taEmp', taEmp);
function taEmp() {
return {
restrict: 'E',
scope: {
ngModel: '=',
ngDisabled: '=',
ngReadonly: '=',
ngChange: '&',
},
templateUrl: 'app/pages/ESS-TA/Common/Directives/TAEmpPicker.html',
}
})();
My Directive in page :
<ta-emp ng-model="empCode" ng-change="OnChange()"></ta-emp>
My directive not call function in controller
I made it work by using $watch inside your directive and parsing an controller function as param into it. The function gonna be executed once the input value has changed.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.name = '';
$scope.someFunction = function (data) {
console.log(data);
};
});
myApp.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
model: '=ngModel',
function: '='
},
template: '<input type="text" ng-model="model" function="function" my-directive>',
link: function (scope, element, attrs) {
scope.$watch('model', function (newValue, oldValue) {
if (newValue && newValue !== oldValue) {
if (typeof scope.function === 'function') {
scope.function('test');
}
}
}, true);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<my-directive ng-model="name" function="someFunction"></my-directive>
</div>

Using $uibModalInstance in directive

When opening a bootstrap ui modal, if you prefer to use a directive, rather than separately a templateUrl and controller, how can you then in the controller of the directive for the modal, access $uibModalInstance in order to close the modal or whatever you need to do? Also, how can we pass items without having to add it as an attribute on the template?
angular.module('myModule', ['ui.bootstrap'])
.directive('myDirective', ['$timeout', function ($timeout) {
var controllerFn = ['$scope', '$uibModal', function ($scope, $uibModal) {
$scope.names = ['Mario','Wario','Luigi'];
$scope.openModal = function () {
var modalInstance = $uibModal.open({
animation: true,
template: '<my-modal>',
size: 'lg',
resolve: {
items: function () {
return $scope.names;
}
}
});
};
}];
return {
restrict: 'E',
templateUrl: '/Folder/my-directive.html',
controller: controllerFn,
scope: {
}
};
}])
.directive('myModal', ['$timeout', function ($timeout) {
var controllerFn = ['$scope', function ($scope) {
}];
return {
restrict: 'E',
templateUrl: '/Folder/my-modal.html',
controller: controllerFn,
scope: {
}
};
}]);
I use something like that to send parameter to modal, add an element to array and give it back to directive.
// Directive who open modal
.directive('myDirective', ['$timeout', function ($timeout) {
var controllerFn = ['$scope', '$uibModal', function ($scope, $uibModal) {
// Base array
$scope.names = ['Mario','Wario','Luigi'];
$scope.openModal = function () {
// Modal instance
var modalInstance = $uibModal.open({
animation: true,
template: '<my-modal>',
size: 'lg',
controller: 'myDirectiveModalCtrl',
controllerAs: '$modalController',
resolve: {
// Provide namesInModal as service to modal controller
namesInModal: function () {
return $scope.names;
}
}
});
// When modal close, fetch parameter given
modalInstance.result.then(function (namesFromModal) {
$scope.names = namesFromModal;
}, function () {
// $log.info('Modal dismissed at: ' + new Date());
});
};
}];
return {
restrict: 'E',
templateUrl: '/Folder/my-directive.html',
controller: controllerFn,
scope: {
}
};
}])
// Modal controller
.controller('myDirectiveModalCtrl', ['$uibModalInstance','namesInModal',
function ($uibModalInstance, namesInModal) {
// Use same name set in myDirective.controllerAs
var $modalController = this;
// Get provided parameter as service
$modalController.names = namesInModal;
// Add new element
$modalController.names.push('peach');
// Return modal variable when close
$modalController.ok = function () {
$uibModalInstance.close($modalController.names);
};
$modalController.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
]);
In the directive's link function, $uibModalInstance is available on the scope object.

Set Directive Angular after rendering view

I want to load my Angular Directive when my class change.
I have a directive who get the route and when this directive can get a route she set on a class in a div child.
But when the div child have the class, the directive don't run.
Route directive :
angular.module('myApp').directive('index', ['$rootScope','usersEntity', '$location', '$timeout',function($rootScope,usersEntity, $location, $timeout){
return {
restrict: 'E',
templateUrl: 'index',
replace: true,
controller: function ($scope, $element, $attrs) {
$scope.user = function () {
return usersEntity;
};
$scope.location = function () {
return $location.path().replace('/', '');
};
$rootScope.$on('$locationChangeStart', function (event) {
$scope.routeMap = {
'login': 'users-log'
};
if ($scope.location().length < 1) {
$scope.route = '';
} else {
$.each($scope.routeMap, function (index, value) {
if (index == $scope.location()) {
$scope.route = value;
}
});
}
});
},
link: function() {
}
}
}]);
Thanks and sorry for my perfect English ;)

Call controller of another directive in AngularJs

How can I refer to directive's controller function from $apply in another directive of the same element? Example:
<myelement hint="myelement.controller.getMe()">hoverMe</myelement>
app.directive("myelement", function () {
return {
restrict: "E",
controller: function ($scope) {
this.getMe = function () {
return "me";
};
}
}
});
app.directive("hint", function () {
return {
restrict: "A",
controller: function ($rootScope) {
this.showHint = function (getMsg) {
alert($rootScope.$apply(getMsg)); //what should be written here?
}
},
link: function (scope, element, attrs, controller) {
element.bind("mouseenter", function () {
controller.showHint(attrs.hint);
});
}
}
});
Sources: http://plnkr.co/edit/9qth9N?p=preview
Use require (read more about it here).
app.directive("hint", function () {
return {
restrict: "A",
require: ["myelement", "hint"],
controller: function ($scope) {
this.showHint = function (msg) {
alert($scope.$apply(msg)); //what should be written here?
}
},
link: function (scope, element, attrs, ctrls) {
var myElementController = ctrls[0],
hintController = ctrls[1];
element.bind("mouseenter", function () {
hintController.showHint(myElementController.getMsg());
});
}
}
});
UPDATE (about making Hint universal, see comments below)
To make Hint directive universal, than you could use the $scope as the medium between them.
app.directive("myelement", function () {
return {
restrict: "E",
controller: function ($scope) {
$scope.getMe = function () {
return "me";
};
}
}
});
<myelement hint="getMe()">hoverMe</myelement>
The only change is that the getMe message is not setted in the controller (this.getMe) but in the $scope ($scope.getMe).

Categories

Resources