Disable/re-enable button within isolate scope directive in Angular - javascript

I need to enable/disable a button after click with Angular. When a user clicks "Submit form", it makes an http request. If an error occurs (inside the catch), I want to re-enable the directive button so that a user can try again. I have a directive with controllerAs syntax and isolateScope. Below is the code I have (simplified for here);
myCtrl parent controller (controllerAs is myCtrl)
vm.submit = function() {
MyService
.update()
.then(function(res) {
// success
})
.catch(function(err) {
vm.error = true;
// error
});
};
Parent view with my-form directive
<my-form form-submit='myCtrl.submit()'></my-form>
myForm Directive
function myForm() {
return {
restrict: 'E',
replace: true,
templateUrl: 'myform.html',
scope: {
formSubmit: '&',
},
require: ['form', 'myForm'],
link: function(scope, element, attrs, ctrls) {
var formCtrl = ctrls[0];
var directiveCtrl = ctrls[1];
scope.isButtonDisabled = false;
scope.submit = function() {
scope.submitted = true;
directiveCtrl.submit();
};
},
controller: function($scope, $element, $attrs) {
var vm = this;
// Submit parent function
vm.submit = function() {
vm.formSubmit();
};
},
controllerAs: 'myFormCtrl',
bindToController: true
};
}
angular.module('mymodule')
.directive('myForm', [ myForm ]);
myForm directive template
<form name='myForm' novalidate>
// form fields
<button ng-click='submit()' ng-disabled='isButtonDisabled'>Submit Form</button>
</form>

Instead of having the promise resolved in the parent controller, you could just pass the promise back to the child controller and handle the logic there. Something like this should work:
parent:
vm.submit = function() {
return MyService.update().$promise;
};
child:
vm.submit = function() {
vm.formSubmit().then(function(res) {
// success
})
.catch(function(err) {
vm.error = true;
// error
scope.isButtonDisabled = false;
});
}

Related

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.

How to call another directive from directive angularjs

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.

Angular watch on parent directive's controller with require

I have a parent and child directive with a controller each, both of which are required in the child directive. I want to watch for changes to a property on the parent directive controller within the link function of the child directive. However, the watch function is fired on initialisation but not subsequently when the property is changed by a button in the parent directive's scope, or by the link function of the parent directive.
Please could somebody explain why this is and how I should resolve it?
Parent directive
myApp.directive('parentDirective', function ($timeout) {
return {
restrict: 'E',
scope: true,
controllerAs: 'parentCtrl',
controller: function () {
var vm = this;
vm.someProperty = true;
vm.toggle = function () {
vm.someProperty = !vm.someProperty;
}
},
link: function (scope, element, attrs, controller) {
$timeout(function () {
controller.toggle();
}, 1000);
}
} });
Child directive
myApp.directive('childDirective', function () {
return {
restrict: 'E',
scope: true,
require: ['childDirective', '^parentDirective'],
controllerAs: 'childCtrl',
controller: function () {
var vm = this;
vm.someProperty = '';
},
link: function (scope, element, attrs, controllers) {
var controller = controllers[0];
var parentController = controllers[1];
scope.$watch('parentController.someProperty', function () {
controller.someProperty = parentController.someProperty
? 'Hello world!' : 'Goodbye cruel world';
});
}
}
});
View
<parent-directive>
<button ng-click="parentCtrl.toggle()">Toggle message</button>
<child-directive>
<p>{{childCtrl.someProperty}}</p>
</child-directive>
</parent-directive>
Fiddle.
On the scope you're watching, the parent controller is 'parentCtrl' instead of 'parentController', so you're not actually watching the property you want to be. The following should work:
scope.$watch('parentCtrl.someProperty', function () {
controller.someProperty = parentController.someProperty
? 'Hello world!' : 'Goodbye cruel world';
});

Angular directive click function calling twice

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

angular.js directive two-way-binding scope updating

I wanted to use a directive to have some click-to-edit functionality in my front end.
This is the directive I am using for that: http://icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/
'use strict';
angular.module('jayMapApp')
.directive('clickToEdit', function () {
return {
templateUrl: 'directives/clickToEdit/clickToEdit.html',
restrict: 'A',
replace: true,
scope: {
value: '=clickToEdit',
method: '&onSave'
},
controller: function($scope, $attrs) {
$scope.view = {
editableValue: $scope.value,
editorEnabled: false
};
$scope.enableEditor = function() {
$scope.view.editorEnabled = true;
$scope.view.editableValue = $scope.value;
};
$scope.disableEditor = function() {
$scope.view.editorEnabled = false;
};
$scope.save = function() {
$scope.value = $scope.view.editableValue;
$scope.disableEditor();
$scope.method();
};
}
};
});
I added a second attribute to the directive to call a method after when the user changed the value and then update the database etc. The method (´$onSave´ here) is called fine, but it seems the parent scope is not yet updated when I call the method at the end of the directive.
Is there a way to call the method but have the parent scope updated for sure?
Thanks in advance,
Michael
I believe you are supposed to create the functions to attach inside the linking function:
Take a look at this code:
http://plnkr.co/edit/ZTx0xrOoQF3i93buJ279?p=preview
app.directive('clickToEdit', function () {
return {
templateUrl: 'clickToEdit.html',
restrict: 'A',
replace: true,
scope: {
value: '=clickToEdit',
method: '&onSave'
},
link: function(scope, element, attrs){
scope.save = function(){
console.log('save in link fired');
}
},
controller: function($scope, $attrs) {
$scope.view = {
editableValue: $scope.value,
editorEnabled: false
};
$scope.enableEditor = function() {
$scope.view.editorEnabled = true;
$scope.view.editableValue = $scope.value;
};
$scope.disableEditor = function() {
$scope.view.editorEnabled = false;
};
$scope.save = function() {
console.log('save in controller fired');
$scope.value = $scope.view.editableValue;
$scope.disableEditor();
$scope.method();
};
}
};
});
I haven't declared the functions inside the controller before, but I don't see why it wouldn't work.
Though this question/answer explain it Link vs compile vs controller
From my understanding:
The controller is used to share data between directive instances, not to "link" functions which would be run as callbacks.
The method is being called but angular doesn't realise it needs to run the digest cycle to update the controller scope. Luckily you can still trigger the digest from inside your isolate scope just wrap the call to the method:
$scope.$apply($scope.method());

Categories

Resources