AngularJS Custom Directive using ng-options populated from service - javascript

I've really hit a brick wall with this, and I know I'm probably missing something here, but I'm stuck and need help. What I'm trying to do is use a service to populate the options in an ng-options directive; however, the ng-options are inside of a custom directive, and I've tried everything from track by, to testing it outside of the directive, inside the directive, etc. Can someone please take a look at this code and see if you can spot what I'm missing? Any help is greatly appreciated. It WILL work as far as executing the update to the ng-model; however, at page landing and record selection, it will not initially select the proper option, but if I take the track by out, it will initialize with the proper selection, it just won't update ng-model when/if I do that.
angular
.module('app')
.controller('mainCtrl', ['acctList', 'CONSTANTS', 'FORMFIELDS', function(acctList, CONSTANTS, FORMFIELDS) {
var mainCtrl = this;
mainCtrl.form = {};
mainCtrl.formFields = FORMFIELDS;
mainCtrl.currentRecord = null;
mainCtrl.editedRecord = {};
mainCtrl.setCurrentRecord = function(value) {
mainCtrl.currentRecord = value;
mainCtrl.editedRecord = angular.copy(mainCtrl.currentRecord);
};
mainCtrl.statuses = CONSTANTS.statuses;
}])
.value('FORMFIELDS', [
{
key: 'active_flag',
inputtype: 'select',
type: 'text',
class: 'form-control',
id: 'activeFl',
name: 'activeFl',
placeholder: 'Active Flag',
required: true,
maxlength: 1,
disabled: false,
labelfor: 'inputActiveFl',
labeltext: 'Active Flag',
field: 'mainCtrl.editedRecord.ACTIVE_FL',
options: 'list as list.desc for list in mainCtrl.statuses track by list.value'
}
])
.value('CONSTANTS',
{
statuses: [
{
id: 1,
value: "Y",
desc: "Active"
},
{
id: 2,
value: "N",
desc: "Inactive"
}
]
}
)
.directive('formTemplate', ['$compile', function($compile) {
function linker(scope, element, attr) {
scope.$watch(attr.modeltemp, function(modeltemp) {
// if ngModel already equals modeltemp or modeltemp doesn't exist, return
if (attr.ngModel == modeltemp || !modeltemp) return;
// remove all attributes to prevent duplication
element.removeAttr('placeholder');
element.removeAttr('type');
element.removeAttr('class');
element.removeAttr('id');
element.removeAttr('name');
element.removeAttr('ng-required');
element.removeAttr('maxlength');
element.removeAttr('ng-disabled');
// add the ng-model attribute presently tied to modeltemp
element.attr('ng-model', modeltemp);
// if modeltemp is blank, then remove ng-model, as it would be null
if (modeltemp == '') {
element.removeAttr('ng-model');
}
// Unbind all previous event handlers, this is
// necessary to remove previously linked models.
element.off();
// run a compile on the element, injecting scope, to reconstruct the element
$compile(element)(scope);
});
console.log(scope.acctCtrl);
}
// dynamic templating function associated with the templateUrl in the DDO
function template (tElement, tAttrs) {
// set the type variable equal to the value from the tAttr for 'inputtype' coming from the view
var type = tAttrs['inputtype'];
// just declaring the return variable for cleanliness
var tpl;
// begin the switch-case statement for each inputtype, then set it's return variable equal to the respective url
switch(type) {
case 'input':
tpl = '/common/directives/formTemplate/formTemplate.template.html';
break;
case 'select':
tpl = '/common/directives/formTemplate/formTemplateSelect.template.html';
break;
default:
tpl = '/common/directives/formTemplate/formTemplate.template.html';
break;
}
return tpl;
}
return {
restrict: 'EA',
replace: true,
templateUrl: template,
link: linker
};
}])
<form class="form-horizontal" ng-submit="submit()" name="mainCtrl.form.newAcctForm">
<div class="col-lg-6 form-fields" ng-repeat="fields in mainCtrl.formFields" ng-class="{ 'has-error': mainCtrl.form.newAcctForm.{{fields.name}}.$dirty }">
<label class="control-label" for="{{fields.labelfor}}">{{fields.labeltext}}</label>
<div form-template modeltemp="fields.field" inputtype="{{fields.inputtype}}"></div>
</div>
</form>
<select class="{{fields.class}}" id="{{fields.id}}" name="{{fields.name}}" ng-options="{{fields.options}}" ng-required="{{fields.required}}" maxlength="{{fields.maxlength}}" ng-disabled="{{fields.disabled}}">
<option value="">Please select...</option>
</select>

While this does work, did you consider using lifecycle hooks instead, waiting until after the view has loaded/initialized? Your solution works, but it's a bit like using a rocket launcher on an ant hill.

Related

AngularJS + select2 - How to set initial value

I want to use Select2 in my AngularJS project, So I added an input like this :
<select class="find-neighborhood js-states form-control"
ng-model="regionIdentifier"
ng-init="">
</select>
Luckily , Whenever regionIdentifier is change, I find out. Actually I want to set initial value in my Select2. Here is my javascript code :
$(".find-neighborhood").select2({
dir: "rtl",
placeholder: "find neighborhood ...",
allowClear: true,
data: $scope.regions
});
My $scope.regions looks like :
[object,object,object]
Each object is like :
0 :Object
id:52623
regionSlug:yvuj
text:yvuj1
How to init value in my select2?
You should create a directive to make this work globally and fine. Here is a simple example which let you initialize a select2 set the default option values to your selection. You can find a working version on plnkr. While select2 depends on jQuery you may will look for an other lib to make it work. Some dev's preffer to have no jQuery included in AngularJS projects.
Controller
//option list
$scope.regions = {
'test1' : {
id: 1
},
'test2' : {
id: 2
},
'test3' : {
id: 3
},
'test4' : {
id: 4
},
'test5' : {
id: 5
}
};
//model & selected value setup
$scope.regionIdentifier = 3;
View
<select class="js-example-basic-single"
ng-model="regionIdentifier"
items="regions"
items-selected="regionIdentifier"
id="regionSelection"
select-two>
</select>
Directive
/**
* Simple select2 directive
*/
angular.module('app').directive('selectTwo', ['$timeout', function($timeout){
return {
restrict : 'EA',
transclude : true,
terminal: true,
templateUrl : 'views/directive/select2.html',
scope: {
items: "=",
itemsSelected: "="
},
link: function($scope, $element, $attrs, $controller){
//format options https://select2.github.io/select2/#documentation
function format(state) {
//init default state
var optionTemplate = state.text;
if (!state.id || state.id == 0) { //option group or no selection item
return optionTemplate;
}
return optionTemplate;
}
//init on load
$timeout(function(){
//if multiple options are possible, parse an comma seperated list into itemsSelected like 1,2,5,23,21
if (angular.isString($scope.itemsSelected) && $scope.itemsSelected.split(',').length > 1) {
$scope.itemsSelected = $scope.itemsSelected.split(',');
}
$($element[0]).select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
}).val($scope.itemsSelected == undefined ? [0]: [$scope.itemsSelected]).trigger("change");
});
}
};
}]);
Directive template views/directive/select2.html
<option ng-repeat="(name, item) in items track by $index"
value="{{ item.id }}">
{{ name }}
</option>

How to insert HTML in focussed textAngular element?

I have multiple textAngular fields in same page with common toolbar and I have created a directive to auto insert some text in textAngular field at current caret position. Now the problem is I can insert the code when there is only one textAngular field. But with multiple textAngular fields, I am unable to find which textAngular field is focussed.
Here is my code :
HTML
<div class="row mrgn20">
<div class="formFld">
<text-angular name="message" ta-target-toolbars="messageToolbar" ng-model="composeEmail.body"></text-angular>
<text-angular name="emailSignature" ta-target-toolbars="messageToolbar" ng-model="composeEmailCtrl.emailSignature.text"></text-angular>
<text-angular-toolbar ta-toolbar="[['uploadAttachment','bold','italics', 'ul', 'insertLink', 'fontSize', 'uploadImage', 'fontColor']]" class="toolbar" name="messageToolbar"></text-angular-toolbar>
</div>
<auto-insert-text options="composeEmailCtrl.autoInsertTextOptions" insert-in="message"></auto-insert-text>
</div>
JS
Controller
function ($scope){
$scope.composeEmailCtrl = {};
$scope.composeEmail ={};
$scope.candidate = {
name : 'Rahul',
company : 'Test Company'
}
$scope.composeEmailCtrl.autoInsertTextOptions = [{
title: 'candidate fullName',
value: scope.candidate.name,
key : 'candidate_fullname'
}, {
title: 'company name',
value: scope.candidate.company,
key : 'company_name'
}];
}
Directive
app.directive('autoInsertText', function(textAngularManager) {
return {
restrict: 'E',
template: '<span translate="insert_auto_text"></span> <span ng-repeat="option in options"><button type="button" ng-bind="option.title" ng-click="insertText($event,option)" unselectable="on"></button></span>',
scope: {
options: "=",
insertIn: "#"
},
link: function(scope, elem, attr) {
var _editorScope = '';
scope.insertText = function(event, option) {
_editorScope = _editorScope || textAngularManager.retrieveEditor(scope.insertIn).scope;
_editorScope.displayElements.text[0].focus();
_editorScope.wrapSelection("insertHTML", option.value, true);
}
}
};
});
The autoInsertText directive takes the insert options and the textangular field name in which the value is to be inserted. I want to support insertion in multiple textAngular fields depending on the current caret position.

Angular change default value of select from filter

I have a select box which is populated with some data from my controller. When an input value changes the contents of the select box should be filtered and a default value should be assigned based on the is default property of the data object.
Is there any way this can be done using angular directives or would it need to be done as a custom filter function doing something along the lines of
angular.forEach(vm.data,function(item){
if (vm.q == item.someId && item.isDefault) {
vm.result = item.value;
}
});
My html looks something like
<div ng-app="myApp" ng-controller="ctrl as vm">
<input type="text" ng-model="vm.q">
<select ng-options="item.value as item.description for item in vm.data | filter:{someId:vm.q}" ng-model="vm.result"></select>
</div>
and my controller looks like:
(function(){
angular.module('myApp',[]);
angular
.module('myApp')
.controller('ctrl',ctrl);
function ctrl()
{
var vm = this;
vm.data = [
{
someId: '1',
description: 'test1',
value: 100,
isDefault: true
},
{
someId: '2',
description: 'test2',
value: 200,
isDefault: false
},
{
someId: '3',
description: 'test3',
value: 100,
isDefault: true
},
];
}
})();
See my plunkr demo here: http://plnkr.co/edit/RDhQWQcHFMQJvwOyHI4r?p=preview
Desired behaviour:
1) Enter 1 into text box
2) List should be filtered to 2 items
3) Select box should pre-select item 1 based on property isDefault set to true
Thanks in advance
I'd suggest you include some 3rd party library, like lodash, into your project to make working with arrays/collections that much easier.
After that you could add ng-change directive for your input.
<input type="text" ng-model="vm.q" ng-change="vm.onChange(vm.q)">
And the actual onChange function in the controller
vm.onChange = function(id) {
var item = _.findWhere(vm.data, { someId: id, isDefault: true });
vm.result = item ? item.value : null;
};
And there you have it.

Angular JS: "Select All" options of "multi-select select box"

I have created a multiselect select box using Angular JS: below is the code for the same:
JS:
$scope.foobars = [{
'foobar_id': 'foobar01',
'name': 'foobar01',
}, {
'foobar_id': 'foobar02',
'name': 'foobar02',
}, {
'foobar_id': 'foobar03',
'name': 'foobar03',
}, {
'foobar_id': 'foobar04',
'name': 'foobar04',
}, {
'foobar_id': 'foobar05',
'name': 'foobar05',
}];
HTML:
<select multiple="multiple" size="5" id="selFooBar" ng-model="foobarName" ng-options="medcenter as medcenter.name for medcenter in medcenters track by medcenter.medcenter_id">
<option selected="selected">Select All</option>
</select>
And the output is :
Question 1: Why am I not getting the default option "Select All" in the list? And How do I get that?
Question 2: How can I Select All optiions on click of "First Option : Select All"??
Please suggest!
If you want to keep the <option> in the <select> element before you add the ng-options you'll have to use transclusion. the ng-options directive doesn't use transclusion, but you can create a custom directive that does. You can do that by utilizing transcludeFn in the directive post compile function:
compile: function(element,attrs) {
return {
post: function(scope, element, attributes, controller, transcludeFn){
transcludeFn(function(clone, scope) {
// prepend the transcluded content to the select
element.prepend(clone);
// set the onclick of the clone to call the selectAll function
clone.bind('click', function(){
clone.scope().$parent.selectAll();
scope.$apply();
})
});
}
}
},
controller: function($scope) {
$scope.selectAll = function() {
$scope.selectedValues = $scope.values;
}
}
Then you can set the selectedValues to all possible values on the scope, whether that's isolate or inherited. In the following plnkr example it's isolated. On click the Select All option will select the other elements.
Plunker Example

ng-repeat controller and parent update

I've been reading a lot on angular scopes and inheritance but I can't get my head around this problem. Here is the HTML I'm using:
<div class="sensorquery-sensor" ng-repeat="sensor in query.sensors" ng-controller="SensorsCtrl">
<select class="form-control"
ng-model="selected.sensor"
ng-options="sensor.name for sensor in parameters.sensors">
</select>
<select class="form-control"
ng-model="selected.definition"
ng-options="definition.value for definition in definitions">
</select>
<select class="form-control"
ng-model="selected.operation"
ng-options="operation for operation in operations">
</select>
</div>
As you can see, I have an ng-repeat based on query.sensors. The values stored in this query.sensors array should be simple:
{
name: 'sensor1',
type: 'temperature'
}
But I want to use a child controller: SensorsCtrl to handle more logic per sensor and hide the complexitiy of sensors. A sensor can look like:
{
name: 'sensor1',
attributes: [
'model',
'brand'
],
definitions: [
{
datatype: 'double',
value: 'temperature'
},
{
datatype: 'integer',
value: 'pressure'
},
{
datatype: 'string',
value: 'color'
}
]
}
So it's in my SensorsCtrl controller where I want to put the selection logic:
$scope.$watch('selected.sensor', function(sensor) {
$scope.definitions = sensor.template.definition;
});
$scope.$watch('selected.definition', function(definition) {
if (definition.datatype === 'string') {
$scope.operations = ['Count'];
} else {
$scope.operations = ['Max', 'Min'];
}
$scope.selected.operation = _.first($scope.operations);
});
How do I keep the link with the parent query.sensors[$index] while transforming the sensor as the user selects different sensors and definitions?
Setting up a watcher on selected and updating the query.sensors array triggers an infinite $digest loop.
I found the solution which was right before my eyes:
<div class="sensorquery-sensor" ng-repeat="sensor in query.sensors" ng-controller="SensorsCtrl">
<!-- ... -->
</div>
The sensor is a reference to the original object of the parent query.sensors. An it's created in the scope of the sub-controller.
So in my SensorsCtrl controller, I can just watch:
$scope.$watch('sensor.definition', function(definition) {
/* ... */
});
So I can put hide some complexity in this controller while maintaining a proper link to the original element.
It does not answer the question of maintaining a less complex object but it's a different question I guess.

Categories

Resources