I am slugify function running smoothly.
What bothers me is having to repeat the function code in all controllers.
There is the possibility of converting into a service, or otherwise I write only once this function?
Today use of this form:
<md-input-container class="md-accent">
<label >Digite o título do Produto</label>
<input ng-model="product.title" ng-change="slugify(product.title)">
</md-input-container>
<md-input-container class="md-accent">
<label>Link permanente</label>
<input ng-model="product.slug" disabled>
</md-input-container>
my slugify function:
$scope.slugify = function(slug){
var makeString = function(object) {
if (object === null) {
return '';
}
return '' + object;
};
var from = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž',
to = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz',
regex = new RegExp('[' + from + ']', 'g');
slug = makeString(slug).toString().toLowerCase().replace(regex, function (c){
var index = from.indexOf(c);
return to.charAt(index) || '-';
}).replace(/[^\w\-\s]+/g, '').trim().replace(/\s+/g, '-').replace(/\-\-+/g, '-');
$scope.product.slug = slug;
};
SOLUTION HERE! FACTORY:
.factory('slugify', function() {
var self = this;
self.generate = function(slug){
var makeString = function(object) {
if (object === null) {
return '';
}
return '' + object;
};
var from = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž',
to = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz',
regex = new RegExp('[' + from + ']', 'g');
slug = makeString(slug).toString().toLowerCase().replace(regex, function (c){
var index = from.indexOf(c);
return to.charAt(index) || '-';
}).replace(/[^\w\-\s]+/g, '').trim().replace(/\s+/g, '-').replace(/\-\-+/g, '-');
return slug;
};
return self;
});
And in controllers:
$scope.slugIt = function(title){
$scope.product.slug = slugify.generate(title);
};
And in views:
<input ng-model="product.title" ng-change="slugIt(product.title)">
You could create a directive, that uses the service to generate a slug.
.factory('slugger', function slugger() {
return {
generateSlug: generateSlug
};
function generateSlug(input) {
var from = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž';
var to = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz';
var regex = new RegExp('[' + from + ']', 'g');
input = makeString(input).toString().toLowerCase().replace(regex, function (c) {
var index = from.indexOf(c);
return to.charAt(index) || '-';
}).replace(/[^\w\-\s]+/g, '').trim().replace(/\s+/g, '-').replace(/\-\-+/g, '-');
return input;
}
function makeString(object) {
if (object === null) {
return '';
}
return '' + object;
}
})
.directive('slugInput', function (slugger) {
return {
require: 'ngModel',
link: function (scope, iElement, iAttrs, ngModelCtrl) {
iElement.on('input', function () {
ngModelCtrl.$setViewValue(slugger.generateSlug(iElement.val()));
ngModelCtrl.$render();
});
scope.$on('$destroy', function () {
iElement.off('input');
});
}
}
});
Usage:
Anywhere in your app,
<input ng-model="product.title" slug-input>
I don't know your exact requirement. But, you can write a service something like this
angular.module('app').service('slugService',
function () {
function serviceInstance() {
var services = {
slugify: slugify,
slug: slug
};
var slug = null;
function slugify(slug) {
var makeString = function (object) {
if (object === null) {
return '';
}
return '' + object;
};
var from = 'ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșšŝťțŭùúüűûñÿýçżźž',
to = 'aaaaaaaaaccceeeeeghiiiijllnnoooooooossssttuuuuuunyyczzz',
regex = new RegExp('[' + from + ']', 'g');
this.slug = makeString(slug).toString().toLowerCase().replace(regex, function (c) {
var index = from.indexOf(c);
return to.charAt(index) || '-';
})
.replace(/[^\w\-\s]+/g, '')
.trim().replace(/\s+/g, '-')
.replace(/\-\-+/g, '-');
}
return services;
}
return new serviceInstance();
}
);
//inject the service in your controller
angular.module('app').controller('urController', function(slugService){
}
and use it in your view
ng-change(slugService.slugify(product.title))
ng-model(slugService.slug) //probably need to use ng-init as well
//assuming the service is used once per page
Related
//when open application then this error show, How can i fix this please explain me.
TypeError: keyboard[extension] is not a function
at Object.attach (ng-virtual-keyboard.js:104)
at Object.link (ng-virtual-keyboard.js:133)
at angular.js:1365
at angular.js:11229
at invokeLinkFn (angular.js:11235)
at nodeLinkFn (angular.js:10554)
at compositeLinkFn (angular.js:9801)
at nodeLinkFn (angular.js:10548)
at compositeLinkFn (angular.js:9801)
at compositeLinkFn (angular.js:9804)
"<input type="text" id="login" name="login" ng-virtual-keyboard="" placeholder="Employee ID" class="fadeIn second ng-pristine ng-untouched ng-valid ng-isolate-scope ui-keyboard-input ui-widget-content ui-corner-all" ng-model="auth.empID" required="" aria-haspopup="true" role="textbox">"
// This is HTML code
<input type="text"id="login"name="login" ng-virtual-keyboard placeholder="Employee ID" class="fadeIn second" ng-model="auth.empID" required>
<input type="password" id="password" ng-virtual-keyboard placeholder="Password" class="fadeIn third" ng-model= "auth.password" required>
<input ng-click="signin(auth)" type="submit" class="fadeIn fourth" value="Log In">
// this is my function in angularjs
$scope.signin = function(valid){
if(valid){
var sign = customerService.validUser($scope.auth);
sign.then(function(data){
if(data.status == "success"){
$scope.val = data;
$localStorage.val = data;
if(data.userdata.usertype == "admin"){
$location.path("/admin");
$rootScope.$emit("callAdmin", {"mydata":data});
}else if(data.userdata.usertype == "user"){
$location.path("/product");
$rootScope.$emit("callClient", {"mydata":data});
}
toastr.info("Welcome !");
}else{
toastr.error("Invalid Credential !");
}
})
}else{
toastr.error("Invalid Credential !");
}
};
//this is ng-virtual-keyboard.js
/**
* ng-virtual-keyboard
* An AngularJs Virtual Keyboard Interface based on Mottie/Keyboard
* #version v0.3.3
* #author antonio-spinelli
* #link https://github.com/antonio-spinelli/ng-virtual-keyboard
* #license MIT
*/
(function (angular) {
angular.module('ng-virtual-keyboard', [])
.constant('VKI_CONFIG', {
})
.service('ngVirtualKeyboardService', ['VKI_CONFIG', function(VKI_CONFIG) {
var clone = function(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null === obj || 'object' !== typeof obj) {
return obj;
}
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = clone(obj[attr]);
}
}
return copy;
}
throw new Error('Unable to copy obj! Its type isn\'t supported.');
};
var executeGetKeyboard = function(elementReference) {
var keyboard;
var element = $(elementReference);
if (element) {
keyboard = $(elementReference).getkeyboard();
}
return keyboard;
};
return {
attach: function(element, config, inputCallback) {
var newConfig = clone(VKI_CONFIG);
config = config || {};
for (var attr in config) {
if (config.hasOwnProperty(attr)) {
newConfig[attr] = config[attr];
}
}
newConfig.accepted = config.accepted || inputCallback;
if (config.autoUpdateModel) {
newConfig.change = config.change || inputCallback;
}
if (newConfig.events) {
var addEventMethod = function(eventName) {
return function(e, kb, el) {
newConfig.events[eventName](e, $(this).data('keyboard'), this);
};
};
for (var eventName in newConfig.events) {
$(element).on(eventName, addEventMethod(eventName));
}
}
var keyboard = $(element).keyboard(newConfig);
if (keyboard && newConfig.extensions) {
for (var extension in newConfig.extensions) {
var extConfig = newConfig.extensions[extension];
if (extConfig) {
keyboard[extension](extConfig);
} else {
keyboard[extension]();
}
}
}
},
getKeyboard: function(elementReference) {
return executeGetKeyboard(elementReference);
},
getKeyboardById: function(id) {
return executeGetKeyboard('#' + id);
}
};
}])
.directive('ngVirtualKeyboard', ['ngVirtualKeyboardService', '$timeout',
function(ngVirtualKeyboardService, $timeout) {
return {
restrict: 'A',
require: '?ngModel',
scope: {
config: '=ngVirtualKeyboard'
},
link: function(scope, elements, attrs, ngModelCtrl) {
var element = elements[0];
if (!ngModelCtrl || !element) {
return;
}
ngVirtualKeyboardService.attach(element, scope.config, function(e, kb, el) {
$timeout(function() {
ngModelCtrl.$setViewValue(element.value);
});
});
scope.$on('$destroy', function() {
var keyboard = $(element).getkeyboard();
if (keyboard) {
keyboard.destroy();
}
});
}
};
}
]);
})(angular);
/**
* ng-virtual-keyboard
* An AngularJs Virtual Keyboard Interface based on Mottie/Keyboard
* #version v0.3.3
* #author antonio-spinelli <antonio.86.spinelli#gmail.com>
* #link https://github.com/antonio-spinelli/ng-virtual-keyboard
* #license MIT
*/
(function (angular) {
angular.module('ng-virtual-keyboard', [])
.constant('VKI_CONFIG', {
})
.service('ngVirtualKeyboardService', ['VKI_CONFIG', function(VKI_CONFIG) {
var clone = function(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null === obj || 'object' !== typeof obj) {
return obj;
}
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = clone(obj[attr]);
}
}
return copy;
}
throw new Error('Unable to copy obj! Its type isn\'t supported.');
};
var executeGetKeyboard = function(elementReference) {
var keyboard;
var element = $(elementReference);
if (element) {
keyboard = $(elementReference).getkeyboard();
}
return keyboard;
};
return {
attach: function(element, config, inputCallback) {
var newConfig = clone(VKI_CONFIG);
config = config || {};
for (var attr in config) {
if (config.hasOwnProperty(attr)) {
newConfig[attr] = config[attr];
}
}
newConfig.accepted = config.accepted || inputCallback;
if (config.autoUpdateModel) {
newConfig.change = config.change || inputCallback;
}
if (newConfig.events) {
var addEventMethod = function(eventName) {
return function(e, kb, el) {
newConfig.events[eventName](e, $(this).data('keyboard'), this);
};
};
for (var eventName in newConfig.events) {
$(element).on(eventName, addEventMethod(eventName));
}
}
var keyboard = $(element).keyboard(newConfig);
if (keyboard && newConfig.extensions) {
for (var extension in newConfig.extensions) {
var extConfig = newConfig.extensions[extension];
if (extConfig) {
keyboard[extension](extConfig);
} else {
//keyboard[extension]();
}
}
}
},
getKeyboard: function(elementReference) {
return executeGetKeyboard(elementReference);
},
getKeyboardById: function(id) {
return executeGetKeyboard('#' + id);
}
};
}])
.directive('ngVirtualKeyboard', ['ngVirtualKeyboardService', '$timeout',
function(ngVirtualKeyboardService, $timeout) {
return {
restrict: 'A',
require: '?ngModel',
scope: {
config: '=ngVirtualKeyboard'
},
link: function(scope, elements, attrs, ngModelCtrl) {
var element = elements[0];
if (!ngModelCtrl || !element) {
return;
}
ngVirtualKeyboardService.attach(element, scope.config, function(e, kb, el) {
$timeout(function() {
ngModelCtrl.$setViewValue(element.value);
});
});
scope.$on('$destroy', function() {
var keyboard = $(element).getkeyboard();
if (keyboard) {
keyboard.destroy();
}
});
}
};
}
]);
})(angular);
****Its working well, i am just comment following line***
//keyboardextension;
but am i right? please answer me !!
My html code is as follows.
<div class="panel-heading">
Select areas to be visited by the operator
<multiselect ng-model="selection" options="areanames" show-search="true"></multiselect>
</div>
My application's controller code is as follows. The function getArea is being called when a user inputs some details in the form (not included here).
this.getArea = function(){
$scope.areanames = [];
$http({
method: "GET",
url: "http://xx.xx.xx.xx/abc",
params:{city:$scope.city,circle:$scope.circle}
}).then(function(success){
for (i = 0; i < success.data.length; i++)
$scope.areanames.push(success.data[i].area);
},function(error){
console.log('error ' + JSON.stringify(error));
});
}
The directive multiselect is written as follows.
multiselect.directive('multiselect', ['$filter', '$document', '$log', function ($filter, $document, $log) {
return {
restrict: 'AE',
scope: {
options: '=',
displayProp: '#',
idProp: '#',
searchLimit: '=?',
selectionLimit: '=?',
showSelectAll: '=?',
showUnselectAll: '=?',
showSearch: '=?',
searchFilter: '=?',
disabled: '=?ngDisabled'
},
replace:true,
require: 'ngModel',
templateUrl: 'multiselect.html',
link: function ($scope, $element, $attrs, $ngModelCtrl) {
$scope.selectionLimit = $scope.selectionLimit || 0;
$scope.searchLimit = $scope.searchLimit || 25;
$scope.searchFilter = '';
if (typeof $scope.options !== 'function') {
$scope.resolvedOptions = $scope.options;
}
if (typeof $attrs.disabled != 'undefined') {
$scope.disabled = true;
}
$scope.toggleDropdown = function () {
console.log('toggleDown');
$scope.open = !$scope.open;
};
var closeHandler = function (event) {
console.log('closeHandler');
if (!$element[0].contains(event.target)) {
$scope.$apply(function () {
$scope.open = false;
});
}
};
$document.on('click', closeHandler);
var updateSelectionLists = function () {
console.log('updateSelectionList');
if (!$ngModelCtrl.$viewValue) {
if ($scope.selectedOptions) {
$scope.selectedOptions = [];
}
$scope.unselectedOptions = $scope.resolvedOptions.slice(); // Take a copy
} else {
$scope.selectedOptions = $scope.resolvedOptions.filter(function (el) {
var id = $scope.getId(el);
for (var i = 0; i < $ngModelCtrl.$viewValue.length; i++) {
var selectedId = $scope.getId($ngModelCtrl.$viewValue[i]);
if (id === selectedId) {
return true;
}
}
return false;
});
$scope.unselectedOptions = $scope.resolvedOptions.filter(function (el) {
return $scope.selectedOptions.indexOf(el) < 0;
});
}
};
$ngModelCtrl.$render = function () {
console.log('render called');
updateSelectionLists();
};
$ngModelCtrl.$viewChangeListeners.push(function () {
console.log('viewChangeListener');
updateSelectionLists();
});
$ngModelCtrl.$isEmpty = function (value) {
console.log('isEmpty');
if (value) {
return (value.length === 0);
} else {
return true;
}
};
var watcher = $scope.$watch('selectedOptions', function () {
$ngModelCtrl.$setViewValue(angular.copy($scope.selectedOptions));
}, true);
$scope.$on('$destroy', function () {
console.log('destroy');
$document.off('click', closeHandler);
if (watcher) {
watcher(); // Clean watcher
}
});
$scope.getButtonText = function () {
console.log('getButtonText');
if ($scope.selectedOptions && $scope.selectedOptions.length === 1) {
return $scope.getDisplay($scope.selectedOptions[0]);
}
if ($scope.selectedOptions && $scope.selectedOptions.length > 1) {
var totalSelected;
totalSelected = angular.isDefined($scope.selectedOptions) ? $scope.selectedOptions.length : 0;
if (totalSelected === 0) {
return 'Select';
} else {
return totalSelected + ' ' + 'selected';
}
} else {
return 'Select';
}
};
$scope.selectAll = function () {
console.log('selectAll');
$scope.selectedOptions = $scope.resolvedOptions;
$scope.unselectedOptions = [];
};
$scope.unselectAll = function () {
console.log('unSelectAll');
$scope.selectedOptions = [];
$scope.unselectedOptions = $scope.resolvedOptions;
};
$scope.toggleItem = function (item) {
console.log('toggleItem');
if (typeof $scope.selectedOptions === 'undefined') {
$scope.selectedOptions = [];
}
var selectedIndex = $scope.selectedOptions.indexOf(item);
var currentlySelected = (selectedIndex !== -1);
if (currentlySelected) {
$scope.unselectedOptions.push($scope.selectedOptions[selectedIndex]);
$scope.selectedOptions.splice(selectedIndex, 1);
} else if (!currentlySelected && ($scope.selectionLimit === 0 || $scope.selectedOptions.length < $scope.selectionLimit)) {
var unselectedIndex = $scope.unselectedOptions.indexOf(item);
$scope.unselectedOptions.splice(unselectedIndex, 1);
$scope.selectedOptions.push(item);
}
};
$scope.getId = function (item) {
console.log('getID');
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.idProp) {
return multiselect.getRecursiveProperty(item, $scope.idProp);
} else {
$log.error('Multiselect: when using objects as model, a idProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.getDisplay = function (item) {
console.log('getDisplay');
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.displayProp) {
return multiselect.getRecursiveProperty(item, $scope.displayProp);
} else {
$log.error('Multiselect: when using objects as model, a displayProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.isSelected = function (item) {
console.log('isSelected');
if (!$scope.selectedOptions) {
return false;
}
var itemId = $scope.getId(item);
for (var i = 0; i < $scope.selectedOptions.length; i++) {
var selectedElement = $scope.selectedOptions[i];
if ($scope.getId(selectedElement) === itemId) {
return true;
}
}
return false;
};
$scope.updateOptions = function () {
console.log('updateOptions');
if (typeof $scope.options === 'function') {
$scope.options().then(function (resolvedOptions) {
$scope.resolvedOptions = resolvedOptions;
updateSelectionLists();
});
}
};
// This search function is optimized to take into account the search limit.
// Using angular limitTo filter is not efficient for big lists, because it still runs the search for
// all elements, even if the limit is reached
$scope.search = function () {
console.log('search');
var counter = 0;
return function (item) {
if (counter > $scope.searchLimit) {
return false;
}
var displayName = $scope.getDisplay(item);
if (displayName) {
var result = displayName.toLowerCase().indexOf($scope.searchFilter.toLowerCase()) > -1;
if (result) {
counter++;
}
return result;
}
}
};
}
};
}]);
When areanames is getting updated asynchronously its values are not getting displayed in multiselect. The inner scope's options value is becoming undefined though I am using '=' with same attribute name i.e., options in the html code.
I'va made a Dropdown directive, i'm trying to assign methods on passing parameter to directive and i'll call these method from controller.
but on first load i'm not getting the assign method in controller but when i'm assigning it on second load (i.e on dropdown change event)and it's working fine.
how can i get the methods on first load of directive in the calling controller after first load.
here is the Directive:
"use strict";
myApp.directive("selectDirective", [function () {
return {
restrict: "E",
template: '<select class="form-control input-sm dropdown" data-ng-model="model.args.selectedItem" data-ng-options="item[model.args.displayField] for item in model.args.source" data-ng-change="model.itemChange(model.args.selectedItem)"><option value="">Select Any Item</option></select>',
scope: {
},
bindToController: { args: "=" },
controller: function () {
var self = this;
var initializeControl = function () {
if (self.args == undefined) {
self.args = {};
}
if (self.args.method == undefined) {
self.args.method = {};
}
if (self.args.isDisabled == undefined) {
self.args.isDisabled = false;
}
if (self.args.displayField == undefined) {
self.args.displayField = '';
//alert('Display Field is blank for dropdown control.')
}
if (self.args.valueField == undefined) {
self.args.valueField = '';
//alert('Value Field is blank for dropdown control.')
}
if (self.args.source == undefined) {
self.args.source = {};
}
if (self.args.hide == undefined) {
self.args.hide = false;
}
}
//here i'm assigning the methods in passing parameter
var assignMethod = function () {
self.args.method =
{
setEnable: function (args) {
self.args.isDisabled = !args;
},
setVisible: function (args) {
self.args.hide = !args;
},
getText: function () {
return self.args.selectedText;
},
getValue: function () {
return self.args.selectedValue;
},
setItem: function (item) {
debugger;
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
}
}
self.itemChange = function (item) {
debugger;
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
initializeControl();
assignMethod();
},
controllerAs: 'model'
}
}]);
Here is the Calling Controller Code:
"use strict";
myApp.controller("homeController", [function () {
var self = this;
var initializeControl = function () {
var myList = [{ id: 1, name: 'List1', value: 'List1' },
{ id: 2, name: 'List2', value: 'List2' }];
self.argsParam = {
displayField: 'name',
valueField: "value",
source: myList,
selectecText: '',
selectecValue: ''
};
self.clickMe = function () {
debugger;
var item = { id: 2, name: 'List2', value: 'List2' };
self.argsParam.method.setItem(item);
}
};
initializeControl();
}]);
View where i used the directive:
<div class="cold-md-12" ng-controller="homeController as model">
<h1>Home Page</h1>
<select-directive args="model.argsParam"></select-directive>
<input type="button" value="Click" ng-click="model.clickMe()" />
</div>
Scenario:
If assigned method called second time inside directive on dropdown-change event then i can get these method on passing param.
i.e
self.itemChange = function (item) {
debugger;
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
// here i'm assigning these method on change event then it's working fine after changing the value otherwise no success
assignMethod();
}
}
So, How i can i get the methods assign in the passing parameter on
First load of the directive?
I've moved the Controller Content to Link function in Directive and
it's working fine, but I still didn't get any idea how my previous code
not worked as expected.
Directive Code:
'use strict';
var testApp = angular.module('TestApp', []);
testApp.directive('sampleDirective', ['$http', function () {
return {
restrict: "E",
scope: {},
bindToController: { args: '=' },
template: '<div class="row">' +
'<select class="form-control"' +
'data-ng-model="model.args.selectedItem"' +
'data-ng-options="item[model.args.displayField] for item in model.args.source"' +
'data-ng-change="model.itemChange(model.args.selectedItem)">' +
'<option value="">Select Any Item</option>' +
'</select>' +
'</div>',
link: function (scope, element, attrs) {
var self = scope.model;
debugger;
var initializeControl = function () {
if (self.args == undefined) {
self.args = {};
}
if (self.args.method == undefined) {
self.args.method = {};
}
if (self.args.isDisabled == undefined) {
self.args.isDisabled = false;
}
if (self.args.displayField == undefined) {
self.args.displayField = '';
alert('Display Field is blank for dropdown control.')
}
if (self.args.valueField == undefined) {
self.args.valueField = '';
alert('Value Field is blank for dropdown control.')
}
if (self.args.source == undefined) {
self.args.source = {};
}
if (self.args.hide == undefined) {
self.args.hide = false;
}
}
var assignMethod = function () {
self.args.method =
{
setEnable: function (args) {
self.args.isDisabled = !args;
},
setVisible: function (args) {
self.args.hide = !args;
},
getText: function () {
return self.args.selectedText;
},
getValue: function () {
return self.args.selectedValue;
},
setItem: function (item) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
};
}
self.itemChange = function (item) {
if (item != undefined) {
var index = self.args.source.indexOf(item);
self.args.selectecText = item[self.args.displayField];
self.args.selectecValue = item[self.args.valueField];
self.args.selectedItem = item;
self.args.selectedIndex = index;
}
}
initializeControl();
assignMethod();
},
controller: function () {
},
controllerAs: 'model'
}
}]);
I am using a directive for auto complete / auto suggest in angular Js taken from http://demo.jankuri.com/ngAutocomplete/. It is working fine getting the data from server and filtering it. But I am facing problem into select and use that select item from the auto complete.
Here is the code of directive what I am using for this...
app.factory('ngAutocompleteService', ['$http', function($http)
{
var self = this;
self.getData = function (url, keyword) {
return $http.get(url, { query: keyword });
};
return self;
}])
app.directive('ngAutocomplete', ['$timeout','$filter','ngAutocompleteService',
function($timeout, $filter, ngAutocompleteService)
{
'use strict';
var keys = {
left : 37,
up : 38,
right : 39,
down : 40,
enter : 13,
esc : 27
};
var setScopeValues = function (scope, attrs) {
scope.url = base_url+attrs.url || null;
scope.searchProperty = attrs.searchProperty || 'skills';
scope.maxResults = attrs.maxResults || 10;
scope.delay = parseInt(attrs.delay, 10) || 300;
scope.minLenth = parseInt(attrs.minLenth, 10) || 2;
scope.allowOnlyResults = scope.$eval(attrs.allowOnlyResults) || false;
scope.placeholder = attrs.placeholder || 'Search...';
};
var delay = (function() {
var timer = 0;
return function (callback, ms) {
$timeout.cancel(timer);
timer = $timeout(callback, ms);
};
})();
return {
restrict: 'E',
require: '?ngModel',
scope: true,
link: function(scope, element, attrs, ngModel) {
setScopeValues(scope, attrs);
scope.results = [];
scope.currentIndex = null;
scope.getResults = function () {
if (parseInt(scope.keyword.length, 10) === 0) scope.results = [];
if (scope.keyword.length < scope.minLenth) return;
delay(function() {
ngAutocompleteService.getData(scope.url, scope.keyword).then(function(resp) {
scope.results = [];
var filtered = $filter('filter')(resp.data, {skills: scope.keyword});
for (var i = 0; i < scope.maxResults; i++) {
scope.results.push(filtered[i]);
}
scope.currentIndex = 0;
if (scope.results.length) {
scope.showResults = true;
}
});
}, scope.delay);
};
scope.selectResult = function (r) {
scope.keyword = r.skills;
ngModel.$setViewValue(r.skills);
scope.ngModel = r.skills;
ngModel.$render();
scope.showResults = false;
};
scope.clearResults = function () {
scope.results = [];
scope.currentIndex = null;
};
scope.hoverResult = function (i) {
scope.currentIndex = i;
}
scope.blurHandler = function () {
$timeout(function() {
if (scope.allowOnlyResults) {
var find = $filter('filter')(scope.results, {skills: scope.keyword}, true);
if (!find.length) {
scope.keyword = '';
ngModel.$setViewValue('');
}
}
scope.showResults = false;
}, 100);
};
scope.keyupHandler = function (e) {
var key = e.which || e.keyCode;
if (key === keys.enter) {
scope.selectResult(scope.results[scope.currentIndex]);
}
if (key === keys.left || key === keys.up) {
if (scope.currentIndex > 0) {
scope.currentIndex -= 1;
}
}
if (key === keys.right || key === keys.down) {
if (scope.currentIndex < scope.maxResults - 1) {
scope.currentIndex += 1;
}
}
if (key === keys.esc) {
scope.keyword = '';
ngModel.$setViewValue('');
scope.clearResults();
}
};
},
template:
'<input type="text" class="form-control" ng-model="keyword" placeholder="{{placeholder}}" ng-change="getResults()" ng-keyup="keyupHandler($event)" ng-blur="blurHandler()" ng-focus="currentIndex = 0" autocorrect="off" autocomplete="off">' +
'<input type="hidden" ng-model="skillIdToBeRated">'+
'<div ng-show="showResults">' +
' <div ng-repeat="r in results | filter : {skills: keyword}" ng-click="selectResult(r)" ng-mouseover="hoverResult($index)" ng-class="{\'hover\': $index === currentIndex}">' +
' <span class="form-control">{{ r.skills }}</span>' +
' </div>' +
'</div>'
};
}]);
I am unable to get value which is selected by ng-click="selectResult(r)" function. The value is showing into text field but not getting it into controller.
I was also using the same directive for showing the auto complete text box. I have tried the following for getting the selected value from auto complete.
in HTML
<div ng-controller="Cntrl as cntrl">
<ng-autocomplete ng-model="cntrl.selectedValue" url="url" search-property="keyword" max-results="10" delay="300" min-length="2" allow-only-results="true"></ng-autocomplete>
</div>
in JavaScript
app.controller('Cntrl', function($scope, $http) {
var self = this;
self.selectedValue = '';
$scope.getSelectedValue = function(){
console.log(self.selectedValue);
}
});
I hope this may help you.
I ran into the same issue. I ended up just watching the property from the details attribute in the ng-autocomplete input and it works pretty well.
$scope.$watch(function() {
return vm.location_result;
}, function(location) {
if (location) {
vm.location_list.push(location);
vm.location = '';
}
});
Fiddle Example: http://jsfiddle.net/n3ztwucL/
GitHub Gist: https://gist.github.com/robrothedev/46e1b2a2470b1f8687ad
Angular newbie here. I have this custom directive that wraps a table row to show information of a tag. When I click 'edit' button in the row, the directive template will be changed and allow the user to update the tag name, when I click 'apply' button, the row will be changed back with the updated tag name, or if I click 'cancel edit' button, the row will be changed back too without any updates. So the editTag and cancelEditTag event function goes like this:
scope.editTag = function() {
scope.originalTagName = scope.tag.name;
element.html(getTemplate(true));
$compile(element.contents())(scope);
};
scope.cancelEditTag = function() {
scope.tag.name = scope.originalTagName;
element.html(getTemplate(false));
$compile(element.contents())(scope);
scope.tagSubmitError = false;
scope.errorMessage = '';
};
Yet when profiling this app using Chrome dev tool, I realized while switching on and off 'edit mode' by clicking 'edit' and 'cancel edit' button, the memory usage keeps climbing up(about 0.1-0.2mb each time), I think I've got a memory leak here, my guess is that after $compile, the old DOM hasn't been released? If so, how should I deal with it? If this is not the case, what else could be the troublemaker? Or is it not a memory leak at all? For the full context, below is the full code for my directive:
app.directive('taginfo', function($compile ,$http) {
var directive = {};
directive.tagSubmitError = true;
directive.errorMessage = '';
directive.originalTagName = '';
directive.restrict = 'A';
directive.scope = {
tag : '=',
selectedTagIds : '=selected',
};
function getTemplate(isEditing) {
if (isEditing) {
return '<th><input type="checkbox" ng-click="selectTag()" ng-checked="selectedTagIds.indexOf(tag.id) != -1"></th>' +
'<th>' +
'<input type="text" class="form-control" ng-model="tag.name" placeholder="请输入标签名称">' +
'<div class="alert alert-danger" style="margin-top: 5px; " ng-show="tagSubmitError" ng-bind="errorMessage"></div>' +
'</th>' +
'<th><span class="label num-post"><%tag.num_items%></span></th>' +
'<th><button class="action-submit-edit" ng-click="submitEditTag()"><i class="icon-ok-2"></i></button> <button class="action-cancel-edit" ng-click="cancelEditTag()"><i class="icon-ban"></i></button></th>';
} else {
return '<th><input type="checkbox" ng-click="selectTag()" ng-checked="selectedTagIds.indexOf(tag.id) != -1"></th>' +
'<th><%tag.name%></th>' +
'<th><span class="label num-post"><%tag.num_items%></span></th>' +
'<th><button class="action-edit" ng-click="editTag()"><i class="icon-pencil"></i></button> <button class="action-delete"><i class="icon-bin"></i></button></th>';
}
}
directive.template = getTemplate(false);
directive.link = function(scope, element, attributes) {
scope.selectTag = function() {
var index = scope.selectedTagIds.indexOf(scope.tag.id);
if (index == -1) {
scope.selectedTagIds.push(scope.tag.id);
} else {
scope.selectedTagIds.splice(index, 1);
}
};
scope.submitEditTag = function() {
if (scope.tag.name.length === 0) {
scope.tagSubmitError = true;
scope.errorMessage = '请输入标签名称';
} else {
$http.post('/admin/posts/edit_tag', {'tagId': scope.tag.id, 'tagName': scope.tag.name}).success(function(data, status, headers, config) {
if (data.statusCode == 'error') {
scope.tagSubmitError = true;
scope.errorMessage = data.errorMessage;
} else if (data.statusCode == 'success') {
scope.tag.name = data.tag_name;
scope.tagSubmitError = false;
scope.errorMessage = '';
element.html(getTemplate(false));
$compile(element.contents())(scope);
}
});
}
};
scope.editTag = function() {
scope.originalTagName = scope.tag.name;
element.html(getTemplate(true));
$compile(element.contents())(scope);
};
scope.cancelEditTag = function() {
scope.tag.name = scope.originalTagName;
element.html(getTemplate(false));
$compile(element.contents())(scope);
scope.tagSubmitError = false;
scope.errorMessage = '';
};
};
return directive;
});
Any help will be appreciated, thanks in advance!
So, I've figured a way to not compile directive template dynamically, thus to avoid memory usage climbing up. That is to add a boolean flag named 'isEditMode' which will be used in ng-if to decide which DOM to show, and the source code is follows:
app.directive('taginfo', function($http, $animate, listService) {
var directive = {};
directive.editTagSubmitError = false;
directive.errorMessage = '';
directive.originalTagName = '';
directive.restrict = 'A';
directive.isEditMode = false;
directive.scope = {
tag : '=',
pagination : '=',
data : '='
};
directive.template = '<th><input type="checkbox" ng-click="selectTag()" ng-checked="data.selectedIds.indexOf(tag.id) != -1"></th>' +
'<th ng-if="isEditMode">' +
'<input type="text" class="form-control" ng-model="tag.name" placeholder="请输入标签名称">' +
'<div class="alert alert-danger" style="margin-top: 5px; " ng-show="editTagSubmitError" ng-bind="errorMessage"></div>' +
'</th>' +
'<th ng-if="!isEditMode"><%tag.name%></th>' +
'<th><span class="label num-posts"><%tag.num_items%></span></th>' +
'<th ng-if="isEditMode"><button class="action-submit-edit" ng-click="submitEditTag()"><i class="icon-ok-2"></i></button> <button class="action-cancel-edit" ng-click="cancelEditTag()"><i class="icon-ban"></i></button></th>' +
'<th ng-if="!isEditMode"><button class="action-edit" ng-click="editTag()"><i class="icon-pencil"></i></button> <button class="action-delete" ng-click="deleteTag()"><i class="icon-bin"></i></button></th>';
directive.link = function(scope, element, attributes) {
scope.selectTag = function() {
listService.selectEntry(scope.tag, scope.data);
};
scope.submitEditTag = function() {
if (!scope.tag.name) {
scope.editTagSubmitError = true;
scope.errorMessage = '请输入标签名称';
} else {
bootbox.confirm('是否确定修改标签名称为' + scope.tag.name +'?', function(result) {
if (result === true) {
$http.post('/admin/posts/edit_tag', {'tagId': scope.tag.id, 'tagName': scope.tag.name}).success(function(response, status, headers, config) {
if (response.statusCode == 'error') {
scope.editTagSubmitError = true;
scope.errorMessage = response.errorMessage;
} else if (response.statusCode == 'success') {
scope.isEditMode = false;
scope.tag.name = response.tag_name;
scope.editTagSubmitError = false;
scope.errorMessage = '';
$animate.removeClass(element, 'editing');
}
});
}
});
}
};
scope.editTag = function() {
scope.isEditMode = true;
scope.originalTagName = scope.tag.name;
if (!element.hasClass('editing')) {
element.addClass('editing');
}
};
scope.cancelEditTag = function() {
scope.isEditMode = false;
scope.tag.name = scope.originalTagName;
scope.editTagSubmitError = false;
scope.errorMessage = '';
};
scope.deleteTag = function() {
listService.deleteEntry(scope.tag, scope.tag.name, scope.data, '/admin/posts/delete_tag', scope.pagination, 'tag');
};
};
return directive;
});
This way, the directive template will not be compiled for editing/non-editing mode repeatedly but only show different DOM based on 'ng-if="isEditMode"'. It solved my problem. Yet I am still wondering if there's a way to remove memory leak for dynamic directive template compilation. Any thoughts would be appreciated.