Focus on an input after creating it with AngularJS - javascript

I've been doing a todo list with AngularJS and want to know if there's a way to focus on a input box after creating it by clicking on a button.
Actually, my save function inside the controller is defined like this:
$scope.save = function() {
$scope.objetivo.$save()
.then(function() {
$scope.message = {
text : 'Saved'
};
$scope.objective = new Objective();
})
.catch(function(err) {
console.log(err.data);
if(err.data.code === 11000) {
text = 'This objective is already registered'
}
$scope.message = {
text : text || "Error when saving"
};
});
};
I think there's might be a way by adding the input box and then focusing on it, but I don't know how to do it.

This fiddle shows you how to implement focus elements even on async logics.
View
<div ng-controller="MyCtrl">
<button ng-click="someAsyncFunction()">
Set focus on async functions
</button>
<input type="text"
set-focus="{{setFocus}}">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $timeout) {
$scope.someAsyncFunction = function ()
//the following timeout indicates ansyc functions.
$timeout(function () {
$scope.setFocus = true;
}, 250);
}
});
myApp.directive('setFocus', function($timeout) {
return {
scope: { trigger: '#setFocus' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if(value === "true") {
$timeout(function() {
element[0].focus();
},250);
}
});
}
};
});

Related

Using different controllers with custom directive in AngularJS?

I have created a search box which is being used on two different views, one is for searching jobs and the other is for searching companies. I have made two separate controllers for both and separate services as well.
Here is the html for the searchbox -
<span class="searchButton"><i class="fa fa-search fa-2x"></i></span>
<input ng-change="companies.search()"
ng-model="companies.searchTerm"
ng-keydown="companies.deleteTerm($event)"
type="text" id="search-box"
style="width: 0px; visibility:hidden;"/>
Here is a script i am using for styling it -
<script type="text/javascript">
var toggleVar = true;
$('.searchButton').on('click', function() {
if(toggleVar) {
$('.searchButton').animate({right: '210px'}, 400);
$('#search-box').css("visibility", "visible");
setTimeout(function() {
$('.searchButton').css("color", "#444444");
}, 200);
$('#search-box').animate({ width: 185 }, 400).focus();
toggleVar = false;
}
else {
$('#search-box').animate({ width: 0 }, 400);
$('.searchButton').animate({right: '25px'}, 400);
setTimeout(function() {
$('.searchButton').css("color", "#eeeeee");
}, 300);
toggleVar = true;
}
});
$('#search-box').focusout(function() {
if(!toggleVar) {
$('#search-box').animate({ width: 0 }, 400);
$('.searchButton').animate({right: '25px'}, 400);
setTimeout(function() {
$('.searchButton').css("color", "#eeeeee");
}, 300);
toggleVar = true;
}
});
</script>
Controller -
angular.module('jobSeekerApp')
.controller('CompaniesallCtrl', ['getAllCompanies', function (companiesService) {
var ctrl = this;
var count;
ctrl.pageNumber = 1;
ctrl.searchPageNumber = 1;
ctrl.isSearching = false;
ctrl.searchTerm = "";
// Initial page load
companiesService.getCompanies(ctrl.pageNumber)
.then(function(response) {
ctrl.companiesList = response.data.results;
count = response.data.count;
checkCount();
}, function(error) {
console.log(error);
});
// User clicks next button
ctrl.getNext = function() {
// If search is not being used
if(ctrl.searchTerm === "" && ctrl.isSearching === false) {
ctrl.pageNumber = ctrl.pageNumber + 1;
companiesService.getCompanies(ctrl.pageNumber)
.then(function(response) {
ctrl.companiesList = ctrl.companiesList.concat(response.data.results);
checkCount();
}, function(error) {
console.log(error);
});
}
// If search is being used
else {
ctrl.searchPageNumber = ctrl.searchPageNumber + 1;
companiesService.searchCompany(ctrl.searchPageNumber, ctrl.searchTerm)
.then(function(response) {
ctrl.companiesList = ctrl.companiesList.concat(response.data.results);
checkCount();
}, function(error) {
console.log(error);
});
}
};
// User backspaces to delete search term
ctrl.deleteTerm = function (event) {
if(event.keyCode === 8) {
ctrl.searchTermLen = ctrl.searchTermLen - 1;
}
// If search box is empty
ctrl.isSearching = ctrl.searchTermLen !== 0;
};
// User clicks search button
ctrl.search = function() {
ctrl.searchTermLen = ctrl.searchTerm.length;
// If search box is empty, show normal results
if(ctrl.searchTerm === "" && ctrl.isSearching === false) {
ctrl.pageNumber = 1;
companiesService.getCompanies(ctrl.pageNumber)
.then(function(response) {
ctrl.companiesList = response.data.results;
count = response.data.count;
checkCount();
}, function(error) {
console.log(error);
});
}
// If search box is not empty, search the input
else {
ctrl.isSearching = true;
ctrl.searchPageNumber = 1;
companiesService.searchCompany(ctrl.searchPageNumber, ctrl.searchTerm)
.then(function(response) {
ctrl.companiesList = response.data.results;
count = response.data.count;
checkCount();
}, function(error) {
console.log(error);
});
}
};
// Function to hide and show next button
function checkCount() {
console.log(count);
$(".nextButton").toggle(count > 10);
count = count - 10;
}
}]);
I am trying to make a directive for this, since all this code is being repeated for the both the views. But how do I make the directive interact with different controllers. And how do i make this part ng-change="companies.search()" ng-model="companies.searchTerm" ng-keydown="companies.deleteTerm($event)" not dependent on the controllers.
I am new to angular and am not sure if this is the right approach or should i let the keep the code separate? Please help.
Server-Side search logic makes it simple
If it is possible that your search logic resides on the server and searching jobs or companies could be distinguished by simply setting a query variable in the URL, then it easy. You could use 1 search directive with an attribute to say which module to search and include this in your HTTP request.
Client-Side search logic slightly more angularjs
If you need different client-side logic for each type of search, consider this approach where there is 1 common search directive, plus 1 directive for each customized search.
the common search directive controls view + common search functionality
a search-companies directive that is restrict: 'A' and require: 'search' and performs functions specific to the company search
a search-jobs directive that is also restrict: 'A' and require: 'search' and performs functions specific to the job search
The concept is that the custom search directives will provide their controller/api object to the common search directive. The common search directive handles the view-controller interaction and calls the provided API functions for customized search functionality.
In Code, this could look something like:
angular.module('SearchDemo', [])
.directive('search', function(){
return {
restrict: 'E',
templateUrl: '/templates/search.tpl.html',
controller: ['$scope', function($scope){
$scope.results = [];
this.setSearchAPI = function(searchAPI){
this.api = searchAPI;
};
$scope.doSearch = function(query){
$scope.results.length = 0;
// here we call one of the custom controller functions
if(this.api && angular.isFunction(this.api.getResults)){
var results = this.api.getResults(query);
// append the results onto $scope.results
// without creating a new array
$scope.results.push.apply($scope.results, results);
}
};
}]
};
})
.directive('searchCompanies', function(){
return {
restrict: 'A',
require: ['search', 'searchCompanies'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-companies controller
// to the common search controller
Ctrl[0].setSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for company search
};
}]
};
})
.directive('searchJobs', function(){
return {
restrict: 'A',
require: ['search', 'searchJobs'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-jobs controller
// to the common search controller
Ctrl[0].setSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for job search
};
}]
};
});
And using it in template would look like:
<search search-companies></search>
and
<search search-jobs></search>
Multiple searches on one directive
This concept could be easily expanded if you need to have one search directive that searches both companies and jobs.
The change would be to turn the search controller's this.api into an array.
angular.module('SearchDemo', [])
.directive('search', function(){
return {
restrict: 'E',
templateUrl: '/templates/search.tpl.html',
controller: ['$scope', function($scope){
$scope.results = [];
// this.api is now an array and can support
// multiple custom search controllers
this.api = [];
this.addSearchAPI = function(searchAPI){
if(this.api.indexOf(searchAPI) == -1){
this.api.push(searchAPI);
}
};
$scope.doSearch = function(query){
$scope.results.length = 0;
// here we call each of the custom controller functions
for(var i=0; i < this.api.length; i++){
var api = this.api[i];
if(angular.isFunction(api.getResults)){
var results = api.getResults(query);
$scope.results.push.apply($scope.results, results);
}
}
};
}]
};
})
.directive('searchCompanies', function(){
return {
restrict: 'A',
require: ['search', 'searchCompanies'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-companies controller
// to the common search controller
Ctrl[0].addSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for company search
};
}]
};
})
.directive('searchJobs', function(){
return {
restrict: 'A',
require: ['search', 'searchJobs'],
link: function(scope, elem, attr, Ctrl){
// here we pass the custom search-jobs controller
// to the common search controller
Ctrl[0].addSearchAPI(Ctrl[1]);
},
controller: ['$scope', function($scope){
// you need to design your common search API and
// implement the custom versions of those functions here
// example:
this.getResults = function(query){
// TODO: load the results for job search
};
}]
};
});
And using it in template would look like:
<search search-companies search-jobs></search>
You will have to pass your data source or service to the directive and bind the events from there.
<body ng-app="customSearchDirective">
<div ng-controller="Controller">
<input type="text" placeholder="Search a Company" data-custom-search data-source="companies" />
<input type="text" placeholder="Search for People" data-custom-search data-source="people" />
<hr>
Searching In: {{ searchSource }}
<br/>
Search Result is At: {{ results }}
</div>
</body>
In this sample I am using data-source to pass an array but you can use a service of course.
Then your directive should use the scope attribute to assign what you passed as parameter in source to the scope of the directive.
You will have the input that is using the directive in the elem parameter to bind all the parameters your desire.
(function(angular) {
'use strict';
angular.module('customSearchDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.companies = ['Microsoft', 'ID Software', 'Tesla'];
$scope.people = ['Gill Bates', 'Cohn Jarmack', 'Melon Musk'];
$scope.results = [];
$scope.searchSource = [];
}])
.directive('customSearch', [function() {
function link(scope, element, attrs) {
element.on("change", function(e) {
var searchTerm = e.target.value;
scope.$parent.$apply(function() {
scope.$parent.searchSource = scope.source;
scope.$parent.results = scope.source.indexOf(searchTerm);
});
});
}
return {
scope: {
source: '='
},
link: link
};
}]);
})(window.angular);
Using scope.$parent feels a bit hacky I know and limits the use of this directive to be a direct child of the controller but I think it's a good way to get you started.
You can try it out: https://plnkr.co/edit/A3jzjek6hyjK4Btk34Vc?p=preview
Just a couple of notes from the example.
The change event work after you remove focus from the text box (not while you're typing
You will have to search the exact string to get a match
Hope it helps.

AngularJS $timeout service

I have to have something visible for 3-4 seconds. I am trying to use $timeout for achieving that. Here's what I got so far:
$timeout(function() {
debugger;
$scope.$on(broadcastService.topErrorBar.show,
function(event, message) {
$scope.rootElement.addClass('is-visible');
$scope.isVisible = true;
$scope.message = message;
});
}, 3000);
$timeout.cancel(function() {
$scope.close();
});
$scope.close = function() {
$scope.rootElement.removeClass('is-visible');
$scope.isVisible = false;
};
This is not working and I'm not able to resolve the issue. What am I doing wrong? Should I use a timeout in this case.
what about:
$scope.$on(broadcastService.topErrorBar.show,
function(event, message) {
$scope.isVisible=false;
$timeout(function () { $scope.isVisible= true; }, 3000);
});
you have to use in html ng-show="isVisible">
It should be like this :
$scope.$on(broadcastService.topErrorBar.show,
function(event, message) {
$scope.rootElement.addClass('is-visible');
$scope.isVisible = true;
$scope.message = message;
$timeout(function() {
$scope.close();
}, 3000);
$scope.close = function() {
$scope.rootElement.removeClass('is-visible');
$scope.isVisible = false;
};
On Broadcast , make element visible , start a timeout so that after 3 seconds $scope.close will be called. No need for $timeout.cancel in your case.
Your logic is inverted. The function in a timeout fires after the time has elapsed. You want the element to be visible, and then set visibility to false in your timeout function. Here's an example.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.visible = true;
$timeout(function () {
$scope.visible = false;
}, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
This is always visible.
<span ng-show="visible">This should hide after 3 seconds</span>
</div>

Angularjs watch on Service Variable from directive best Practice

i'm trying to display a Bootstrap modal Dialog when a Variable in a Service is changed.
I'm currently doing this with broadcast. I'm new to angular so any help to improve my code is appreciated.
This Code works but i wanted to know if this is the correct way to do this.
My Service:
utils.service('UtilsService', function ($rootScope) {
this.objectToDelete = "";
this.deleteMessage = "";
this.DeleteObject = function (object, message) {
this.objectToDelete = object;
this.deleteMessage = message;
$rootScope.$broadcast('objectChanged', this.objectToDelete);
}
});
My Directive:
verwaltungApp.directive('deletedialog', ['UtilsService', function (UtilsService) {
return {
restrict: 'E',
controller: function ($scope, $attrs, UtilsService) {
$scope.$on("objectChanged", function (event, args) {
if (UtilsService.objectToDelete) {
$scope.ObjectToDelete = UtilsService.objectToDelete;
$scope.Message = UtilsService.deleteMessage;
$('#modalErrorDialog').modal('show');
}
});
$scope.DeleteObject = function () {
$scope.ObjectToDelete.Delete();
$scope.ObjectToDelete = null;
$('#modalErrorDialog').modal('hide');
}
$scope.Cancel = function () {
$scope.ObjectToDelete = null;
$('#modalErrorDialog').modal('hide');
}
},
templateUrl: '/shared/DeleteDialog'
};
}]);
I tried it with $watch before but that did not work for me.
The main thing i want to do is to place this directive on my Layout Page so i can call it from any controller with an object i want to delete.

Unit test an AngularJS document ready function

I'm writing an AngularJS application and I'm searching for a way to unit test every single aspect.
In this particular case, I need to unit test a custom directive which I've written that represents a control.
The directive can be found here:
var officeButton = angular.module('OfficeButton', []);
officeButton.directive('officeButton', function() {
return {
restrict: 'E',
replace: false,
scope: {
isDefault: '#',
isDisabled: '#',
control: '=',
label: '#'
},
template: '<div class="button-wrapper" data-ng-click="onClick()">' +
'<a href="#" class="button normal-button">' +
'<span>{{label}}</span>' +
'</a>' +
'</div>',
controller: ['$scope', function($scope) {
var event = this;
var api = {
changeLabel: function(label) {
$scope.label = label;
},
enable: function() {
$scope.isDisabled = false;
},
disable: function() {
$scope.isDisabled = true;
},
setAsDefault: function() {
$scope.isDefault = true;
},
removeDefault: function() {
$scope.isDefault = false;
}
};
event.onClick = function() {
if (typeof $scope.control.onClick === 'function') { $scope.control.onClick(); }
};
$.extend($scope.control, api);
function Init() {
if ($scope.isDefault === 'true') { $scope.isDefault = true; }
else { $scope.isDefault = false; }
}
Init();
}],
link: function(scope, element, attributes, controller) {
scope.$watch('isDefault', function(value) {
if (value === 'true' || value) { $('a', element).addClass('button-default'); }
else { $('a', element).removeClass('button-default'); }
});
scope.onClick = function() { controller.onClick(); }
}
}
});
This directive can be called by using the following HTML snippet:
<office-button label="Office Web Controls" control="buttonController"></office-button>
Now, this directive exposes an API which functions such as changeLabel, enable, disable, ....
Now, those functions are not defined on the load of the application, meaning if at the bottom of my HTML I call the following code:
$scope.buttonController.changeLabel('Office Web Controls for Web Applications Directive Demo');
It will throw an error because the changeLabel() method is not defined.
In order to make it function, I need to wrap those calls in an angular.ready function, such as:
angular.element(document).ready(function () {
$scope.buttonController.changeLabel('Office Web Controls for Web Applications Directive Demo');
});
Here's a plunker for your information.
Now, I'm writing unit tests using Jasmine, and here's what I have for the moment:
describe('Office Web Controls for Web Applications - Button Testing.', function() {
// Provides all the required variables to perform Unit Testing against the 'button' directive.
var $scope, element;
var buttonController = {};
// Loads the directive 'OfficeButton' before every test is being executed.
beforeEach(module('OfficeButton'));
// Build the element so that it can be called.
beforeEach(inject(function($rootScope, $compile) {
// Sets the $scope variable so that it can be used in the future.
$scope = $rootScope;
$scope.control = buttonController;
element = angular.element('<office-button control="buttonController"></office-button>');
$compile(element)($scope);
$scope.$digest();
}));
it('Should expose an API with certain functions.', function() {
});
});
Now, in the it function, I would like to test if the $scope.control does expose the API as defined in the directive.
The problem is that the page needs to be ready before the API is available.
Any tought on how to change the code or how to unit test this correctly?
I've found the issue, it was just a wrong configuration on the unit test.
When using this code:
$scope.control = buttonController;
element = angular.element('<office-button control="buttonController"></office-button>');
I must change the element to:
$scope.control = buttonController;
element = angular.element('<office-button control="control"></office-button>');

My unsaved changes directive needs to work for all forms with different names

I have a directive that opens a modal to alert user of unsaved changes and I need it to check for form dirty with different unknown names. I have tried to use scope to access the forms name and this but have not been successfull. I can access the form name with elem[0].name but it does not carry the form $dirty value.
<form class="form-inline" role="form" name="myFormName" confirm-on-exit>
Cool form html
</form>
app.directive('confirmOnExit', ['modalService', '$rootScope', '$stateParams', '$state', function (modalService, $rootScope, $stateParms, $state) {
return {
restrict: 'A',
link: function (scope, elem, attrs, formCtrl) {
onRouteChangeOff = $rootScope.$on('$stateChangeStart', routeChange);
function routeChange(event, newState, newParams, fromState, fromParams) {
if (scope.myFormName.$dirty) {
return;
}
event.preventDefault();
var modalOptions = {
closeButtonText: 'No, I\'ll stay and save them.',
actionButtonText: 'Yes, Leave and Ignore Changes',
headerText: 'Unsaved Changes',
bodyText: 'You have unsaved changes. Do you want to leave the page?'
};
modalService.showModal({}, modalOptions).then(function (result) {
if (result) {
onRouteChangeOff(); //Stop listening for location changes
$state.go(newState); //Go to page they're interested in
} else {
$state.go(fromState); //Stay on the page and have tab revert to fromState
}
});
return;
}
}
};
}]);
I would suggest creating a service for observing route changes where you register all forms you want to spy on. The registration of a form will then be handled by your directive.
I put together some code below:
app.directive('confirmOnExit', function (FormChanges) {
return {
restrict: 'A',
link: function (scope, elem, attrs, formCtrl) {
FormChanges.register(scope, attrs.name);
}
};
}]);
app.factory('FormChanges', function (modalService, $rootScope, $state) {
var formNames = [];
var dirtyCallbacks = {};
$rootScope.$on('$stateChangeStart', function (event, newState, newParams, fromState, fromParams) {
var hasDirtyForm = false;
// Check all registered forms if any of them is dirty
for (var i = 0; i < formNames.length; i++) {
var name = formNames[i];
if (dirtyCallbacks[name] && dirtyCallbacks[name]()) {
// got a dirty form!
hasDirtyForm = true;
break;
}
}
if (!hasDirtyForm) {
// Nothing is dirty, we can continue normally
return;
}
// Something was dirty, show modal
event.preventDefault();
var modalOptions = {
closeButtonText: 'No, I\'ll stay and save them.',
actionButtonText: 'Yes, Leave and Ignore Changes',
headerText: 'Unsaved Changes',
bodyText: 'You have unsaved changes. Do you want to leave the page?'
};
modalService.showModal({}, modalOptions).then(function (result) {
if (result) {
// clear the current forms
formNames = [];
dirtyCallbacks = {};
$state.go(newState, newParams); //Go to page they're interested in
} else {
$state.go(fromState, fromParams); //Stay on the page and have tab revert to fromState
}
});
return;
});
$rootScope.$on('$stateChangeSuccess', function () {
// be sure to clear the registered forms when change was successful
formNames = [];
dirtyCallbacks = {};
});
var service = {
// Register a form by giving the scope it's contained in and its name
register: function (scope, name) {
scope.$on('$destroy', function () {
// e.g. an ng-if may destroy the scope, so make sure to remove this form again
service.remove(name);
});
formNames.push(name);
dirtyCallbacks[name] = function () {
return scope[name].$dirty;
};
},
remove: function (name) {
delete dirtyCallbacks[name];
}
};
return service;
});
I wasn't able to test it, so it may contain some small errors - just let me know and I will check. Also note that my code is not minification save!
Try using scope.$eval(attrs.name) to get the variable associated with the name in the name attribute. It should behave just like the normal scope variable and you should be able to access all of its properties.
This snippet shows that checking for $dirty works:
angular.module('test', [])
.directive('testdirective', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs, formCtrl) {
console.log(scope.$eval(attrs.name), scope.$eval(attrs.name).$dirty);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Open Console
<div ng-app="test">
<form testdirective name="testform"></form>
</div>

Categories