Angular directive click function calling twice - javascript

Below are the two directive. My problem is that the function addSectorAttributes in my second directive is been fired twice on ng-click from project_subtypes.html.
.directive('projectFilter', function($compile, $timeout){
return {
restrict: 'E',
templateUrl: 'project_filter.html',
link : function(scope,element, attr){
//getting data and fill the html from a service
},
controller: function ($scope) {
$scope.addSubTypes = function (event,id) {
var ex = $(event.currentTarget);
var el = $compile( "<project-subtypes typeid="+id+" class='slide-content'></project-subtypes>" )( $scope );
ex.parent().append(el);
};
}
}
})
.directive('projectSubtypes', function($compile){
return {
restrict: 'E',
scope: true,
templateUrl: 'project_subtypes.html',
link : function(scope,element,attr){
//getting data and fill the html from a service
var id = attr.typeid;
sectorFiltering.getSectorSubTypes(id).success(function(data) {
scope.sector_subtypes = data.sector_subtypes;
});
});
},
controller: function ($scope) {
$scope.addSectorAttributes = function (event,id) {
console.log("teeest"); // called twice.....
};
}
}
})
project_subtypes.html
<li ng-repeat="subtype in substype.subtypes">
<div layout='row' class='load-attributes' ng-click=" addSectorAttributes($event, subtype.id)"></div>
</li>
Any help please....

If the directive function called twice if one time it does not give you the subtype.id and next time if it gives you subtype.id then you just only need to add condition in your directive like as below.
subtype.id&&addSectorAttributes($event, subtype.id)"
Regards,
Mahenrdra

Related

how to get arguments in directive

I have a button and when I click on that function I need to call a directive.
For this I have writern the following code.before creating directive there is a ng-change function.I have removed ng-change and kept directive as follows,
<button upload-file="selectedDocumentName,loanFolderNumber" ><!-- ng-click="uploadFile(selectedDocumentName,FolderNumber)" -->
How can I take that arguments selectedDocumentName,FolderNumber in my directive.I have tried in the following way,but I am not getting the values.
Directive:-
app.directive('uploadFile',['documentService',function(documentService){
return {
restrict: 'AE',
scope: {
selectedDocumentName: '=',
FolderNumber: '=',
},controller: function($scope){
$scope.selectedDocumentName;
},
link : function($scope,element,attrs){
element.on('click',function(e){
})
}
}
}]);
Try this
<button upload-file obj="obj">A</button>
var myApp = angular.module('myApp',[]);
myApp.directive('uploadFile', function() {
return {
restrict: 'AE',
scope: {
obj1: '='
},controller: function($scope){
$scope.obj2 = JSON.parse(JSON.stringify($scope.obj1))
console.log($scope.obj2.selectedDocumentName);
$scope.obj2.selectedDocumentName = "DEF";
console.log($scope.obj2.selectedDocumentName);
},
link : function($scope,element,attrs){
element.on('click',function(e){
})
}
}
});
myApp.controller('MyCtrl', function ($scope) {
$scope.obj = {selectedDocumentName : "ABC",loanFolderNumber : "DEDF"};
});
Check this fiddle

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.

Accessing directive function from controller using $scope.$parent.$$childHead.functionName in AngularJS

I have created a directive.
angular.module('app')
.directive('navtree', function (service) {
return {
restrict: 'A',
scope: {},
link: function (scope, el) {
scope.loadNavtree = function(){
service.data()
.then(function (data) {
///Do something
});
}
scope.loadNavtree();
}
};
});
from my controller I can access the method using
$scope.$parent.$$childHead.loadNavtree();
Though this is working, I feel that this is not the right approach. I want to understand what are the disadvantages of accessing function defined in directive from your controller like this.
I looked this link but I was not able to follow
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
/// How to call takeTablet() available in directive from here?
});
app.directive('focusin', function factory() {
return {
restrict: 'E',
replace: true,
template: '<div>A:{{internalControl}}</div>',
scope: {
control: '='
},
link : function (scope, element, attrs) {
scope.takeTablet = function() {
alert('from directive');//
}
}
};
});
this is not the correct approach because angular do not recommend to use its private variable to access to directive function so you need to get a good approach to do that here is an example to access the directive function from controller.
If you want to use isolated scopes you can pass a control object using bi-directional binding ('=') of a variable from the controller scope. In this way you can control also several instances of the same directive on a page.
plunkr
Controller/Directive:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.focusinControl = {
};
});
app.directive('focusin', function factory() {
return {
restrict: 'E',
replace: true,
template: '<div>A:{{internalControl}}</div>',
scope: {
control: '='
},
link : function (scope, element, attrs) {
scope.internalControl = scope.control || {};
scope.internalControl.takenTablets = 0;
scope.internalControl.takeTablet = function() {
scope.internalControl.takenTablets += 1;
}
}
};
});
HTML:
<button ng-click="focusinControl.takeTablet()">Call directive function</button>
<h4>In controller scope:</h4>
{{focusinControl}}
<h4>In directive scope:</h4>
<focusin control="focusinControl"></focusin>
<h4>Without control object:</h4>
<focusin></focusin>

How to get isolated scope of a directive with ngrepeat and two way bind?

How we can get particular isolated scope of the directive while calling link function from controller(parent)?
I am having a directive and repeating it using ng-repeat. Whenever a button in the directive template is clicked it will call a function- Stop() in directive controller which in-turn calls function test() in parent controller, inside test() it will call a method dirSample () in directive's link function.
When I print the scope inside dirSample(), it prints the scope of the last created directive not the one which called it.
How can I get the scope of the directive which called it?
Find the pluker here
.directive('stopwatch', function() {
return {
restrict: 'AE',
scope: {
meri : '&',
control: '='
},
templateUrl: 'text.html',
link: function(scope, element, attrs, ctrl) {
scope.internalControl = scope.control || {};
scope.internalControl.dirSample = function(){
console.log(scope)
console.log(element)
console.log(attrs)
console.log(ctrl)
}
},
controllerAs: 'swctrl',
controller: function($scope, $interval)
{
var self = this;
self.stop = function()
{
console.log($scope)
$scope.meri(1)
};
}
}});
full code in plunker
I've changed the binding of your function from & to = since you need to pass a parameter. This means some syntax changes are in order, and also you need to pass the scope along the chain if you want to have it all the way at the end:
HTML:
<div stopwatch control="dashControl" meri="test"></div>
Controller:
$scope.test = function(scope)
{
console.log(scope);
$scope.dashControl.dirSample(scope);
}
Directive:
.directive('stopwatch', function() {
return {
restrict: 'AE',
scope: {
meri : '=',
control: '='
},
templateUrl: 'text.html',
link: function(scope, element, attrs, ctrl) {
scope.internalControl = scope.control || {};
scope.internalControl.dirSample = function(_scope){
console.log(_scope);
}
},
controllerAs: 'swctrl',
controller: function($scope, $interval)
{
var self = this;
self.stop = function()
{
console.log($scope);
$scope.meri($scope);
};
}
}});
Plunker

AngularJS: Watch a property of the parent scope

I'm quite new to AngularJS and I'm trying to understand a few things.
First of all, I have my controller of which I will place a snippet here:
var OfficeUIRibbon = angular.module('OfficeUIRibbon');
// Defines the OfficeUIRibbon controller for the application.
OfficeUIRibbon.controller('OfficeUIRibbon', ['$scope', '$http', function($scope, $http) {
var ribbon = this;
ribbon.setApplicationMenuAsActive = function() {
ribbon.applicationMenuActive = true;
}
}
Then I have a directive:
var OfficeUIRibbon = angular.module('OfficeUIRibbon');
OfficeUIRibbon.directive('ribbonApplicationMenu', function() {
return {
restrict: 'E',
replace: false,
scope: {
data: '#'
},
templateUrl: function(element, attributes) {
return attributes.templateurl;
}
}
});
The directive is called like this:
<ribbon-application-menu templateUrl="/OfficeUI.Beta/Resources/Templates/ApplicationMenu.html" data="/OfficeUI.Beta/Resources/JSon/Ribbon/ribbon.json"></ribbon-application-menu>
This does all work and in my template for the directive, the following is placed:
<div id="application" id="applicationMenuHolder" ng-controller="OfficeUIRibbon as OfficeUIRibbon" ng-show="OfficeUIRibbon.applicationMenuActive"...
From inside another element, when I execute a click a function on my controller is executed:
ng-click="OfficeUIRibbon.setApplicationMenuAsActive()"
Here's the directive from the other element:
OfficeUIRibbon.directive('ribbon', function() {
return {
restrict: 'E',
replace: false,
scope: {
data: '#'
},
templateUrl: function(element, attributes) {
return attributes.templateurl;
}
}
});
This function does change the property "applicationMenuActive" on the ribbon itself, which should make the item in the directive template show up.
However, this is not working. I'm guessing I need to watch this property so the view get's updated accordingly.
Anyone has an idea on how this could be done?

Categories

Resources