Change selected value in md-autocomplete in angular material - angularjs

I using md-autocomplete in my page, Now I need to edit a record, how to change selected value in md-autocomplete programmatically?
This is angular code:
app.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($timeout, $q, $log) {
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.states = loadAll();
self.querySearch = querySearch;
function querySearch(query) {
var results = query ? self.states.filter(createFilterFor(query)) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) != -1);
};
}
function loadAll() {
return totlaTablaeau.map(function (repo) {
repo.value = repo.address.toLowerCase();
return repo;
});
}
};

Here's a CodePen using the online docs example. You just need to set the value of md-selected-item.
Markup
<md-autocomplete ... md-selected-item="ctrl.selectedItem" ...></md-autocomplete>
...
<md-button class="md-raised md-primary" ng-click="ctrl.selectArkansas()">Select Arkansas</md-button>
JS
self.selectArkansas = function() {
self.selectedItem = {
value: "Arkansas".toLowerCase(),
display: "Arkansas"
};
}

Your Html template looks like this.
<md-autocomplete
md-selected-item="model"
md-search-text="search_text"
md-items="item in searchResults()"
md-item-text="item.title"
md-min-length="3"
md-floating-label="Your Label"
placeholder="placeholder"
>
<md-item-template>
<span> {{item.title}},{{item.name}}</span>
</md-item-template>
<md-not-found>
No matches found.
</md-not-found>
</md-autocomplete>
Your controller code
class Controller {
constructor($service) {
this.$service = $service;
}
//we are init the varible hare.
$onInit() {
this.search_text = "";
//set by defaut value in you auto complete.
this.model = {id:'0000',title:'defalt',name:'Your Name'};
}
}
//function for get data list
// $service this is service function we can define in over services file and we can inject this way
searchResults() {
let { $service, search_text } = this;
return $service.search(search_text).then((data) =>data.list).catch(err =>{ });
}
//Responce data look like this
//[{id:'00h1',title:'test1',name:'harish verma'},
//{id:'00h2',title:'test1',name:'harish verma'},
//{id:'00h3',title:'test1',name:'harish verma'},
//{id:'00h4',title:'test1',name:'harish verma'}];
}
Controller.$inject = [
"Service"
];
export default Controller;
set by defaut value in you auto complete.
this.model = {id:'0000',title:'defalt',name:'Your Name'};

Related

Error while implementing md-autocomplete in angular

After executing the list in md-autoComplete. I am getting this error while searching. I have given controller name as ctrl and included the $timeout, $q, $log, attaching html and js file.
Please let me know how to fix it. Thanks in advance.
error
ionic.bundle.js:26794 TypeError: Cannot read property 'indexOf' of
null
at filterFn (http://localhost:8100/js/guest-controller.js:102:31)
at Array.filter (native)
at Object.querySearch (http://localhost:8100/js/guest-
controller.js:60:41)
at fn (eval at compile
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:27638:15),
<anonymous>:4:344)
at Scope.$eval
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:30395:28)
at de
(https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:11563)
at he
(https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:12420)
at
https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-
material.min.js:13:8834
at processQueue
(http://localhost:8100/lib/ionic/js/ionic.bundle.js:29127:28)
html file
<div class="form_element_grid auto_fill_info">
<label>Company Name</label>
<md-autocomplete
ng-disabled="ctrl.isDisabled"
md-no-cache="true"
md-selected-item="ctrl.selectedItem"
md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item-change="ctrl.selectedItemChange(item)"
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-item-text="item.display"
md-min-length="0"
placeholder="Enter Company Name" required/>
<md-item-template>
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
No states matching "{{ctrl.searchText}}" were found.
<a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
</md-autocomplete>
Js file
var self = this;
$scope.guestDetails = guestData.data;
self.searchText = '';
self.simulateQuery = false;
self.isDisabled = false;
// list of `state` value/display objects
self.states = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.newState = newState;
function newState(state) {
self.states= loadAll();
}
// ******************************
// Internal methods
// ******************************
/**
* Search for states... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
var results = query ? self.states.filter( createFilterFor(query)
) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); },
Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `states` list of key/value pairs
*/
function loadAll() {
var deliverycomp = $scope.guestDetails;
console.log(deliverycomp);
return deliverycomp.map( function (state) {
return {
value: state.guestId,
display: state.guestName
};
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = query;
return function filterFn(state) {
return (state.display.indexOf('lowercaseQuery') === 0);
};
}

Scope from controller does not pass to directive

I have a html like this :
<div id="create-group" ng-controller="groupCreateController">
<div id="container">
<h1>Create group</h1>
<div class="row">
<div class="col-md-4"><input placeholder="Group Name.." ng-model="group.name"></div>
<div class="col-md-8">
<label>Group Description : </label>
<textarea ng-model="group.description"> </textarea>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6">
<usermgr-permission-list group="group"></usermgr-permission-list>
<button type="button" class="btn btn-md btn-primary" ng-click="btnSave_click($event)">SAVE</button>
</div>
<div class="col-sm-6">
<usermgr-user-list group="group"></usermgr-user-list>
</div>
</div>
</div>
</div>
My controller is :
(function (module) {
'use strict';
module.controller('groupCreateController', function ($scope, $rootScope, $routeParams, $location, userGroupService, $mdDialog) {
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group[0].id = info.id;
$scope.group[0].name = info.name;
$scope.group[0].description = info.description;
console.log($scope.group);
// $rootScope.$broadcast('rCube-user-mgt-users-list', info.id);
// $rootScope.$broadcast('rCube-user-mgt-permissions-list', info.id);
}
else {
}
}).catch(function (exception) {
console.error(exception);
});
}
$scope.init();
});
})(angular.module('r-cube-user-mgt.user-group'));
I have two custom directives in the first block of code for user permissions and users. The group scope that i pass with the directive does not contain the values i put in the getUserGroup(id) function. The group name and group description shows up so the scope.group in the controller is filled, however thats not the case once i pass it to my directives. here is the directives code as well :
permissions list :
(function (module) {
'use strict';
module.directive('usermgrPermissionList', function () {
return {
restrict: 'E',
scope:{
group: '='
},
controller: function ($scope, permissionService) {
$scope.updatedPermissions=[];
console.log($scope.group); //it doesnt have the values from the controller ..
if (!$scope.group.hasOwnProperty('permissions')) {
$scope.group.permissions = [];
}
function getData() {
console.log("inside getDAta for permission list" + $scope.group.id;
permissionService.getPermissionsFiltered($scope.group.id).then(function (info) {
if (info && info.length > 0) {
console.log(info);
$scope.group.permissions = info.map(function (a, index, array) {
return {
id: a.id,
name: a.name,
description: a.description,
assigned: a.assigned
};
});
}
}).catch(function (exception) {
console.error(exception);
});
} //end of getData()
$scope.init = function () {
getData();
};
$scope.init();
},
templateUrl: 'r-cube-user-mgt/permission/list/list.tpl.html'
};
});
})(angular.module('r-cube-user-mgt.permission'));
can anyone help?
you cannot assign property to an array like this $scope.group.id = 0;
either make $scope.group object
$scope.group = {};
or add properties to an index
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
So I solved the issue by adding broadcast to send the id when the directive loads. This worked!
in the Group controller i add broadcast and send the group.id
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group.id = info.id;
$scope.group.name = info.name;
$scope.group.description = info.description;
console.log($scope.group);
$rootScope.$broadcast(rCubeTopics.userMgtPermissionLoadData, $scope.group.id);
}
}).catch(function (exception) {
console.error(exception);
});
}
and in the permission directive get that broadcast :
$scope.$on(rCubeTopics.userMgtPermissionLoadData, function (event, id) {
console.log($scope.group.id);
getData();
});

Angular Material Datepicker not returning correct results with Elasticsearch Range Query

I am trying to fetch instances of documnts that I have indexed on local ES server based on temporal range queries that I am creating. My documents have been created from 01-03-2017 to 31-03-2017.
HTTP request:
temporalsearch: temporalsearch
function temporalsearch(beginfrom, beginto) {
console.log("hello");
var _url = 'http://127.0.0.1:9201/_search?';
var b = {
"query": {
"range" : {
"metadata.o2r.temporal.begin" : {
"gte": beginfrom,
"lte": beginto
}
}
}
};
return $http.post(_url,b);
}
Javascript:
function SearchController($scope,$stateParams, $q, $log, httpRequests, $location, searchResults, header, icons, leafletData) {
var beginfrom;
var beginto;
var vm = this;
$scope.beginfromDate = new Date();
$scope.begintoDate = new Date();
vm.beginfromDate = beginfromDate;
vm.begintoDate = begintoDate;
function beginfromDate() {
beginfrom = $scope.beginfromDate;
console.log(JSON.stringify(beginfrom, 'bf'));
}
function begintoDate() {
beginto = $scope.begintoDate;
console.log(JSON.stringify(beginto,'bt'));
}
HTTP call in Javascript:
function callingtemporalsearch() {
console.log('calling temporal search');
var deferred = $q.defer();
httpRequests.temporalsearch(beginfrom, beginto)
.then(cb1)
.catch(errorHandler);
return deferred.promise;
function cb1(response) {
$log.debug('result of search: %o', response);
}
function errorHandler(e) {
$log.debug('search error: %o', e);
deferred.resolve(e);
}
}
HTML:
<md-button ng-click="vm.Button()" class="search-button md-primary md-raised white-font">Temporal1</md-button>
<md-datepicker ng-model='beginfromDate'ng-change="vm.beginfromDate()"></md-datepicker>
<h4>Begin To</h4>
<md-datepicker ng-model='begintoDate'ng-change="vm.begintoDate()" ></md-datepicker>
I want to be able to stop the change directive from searching documents on default values as it returns wrong results.

How to check whether an object is empty in a span?

I have some objects in my angularjs controller.
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.notes = [];
$scope.note = {};
$scope.submit = function() {
$scope.notes.push($scope.note);
$scope.note = {};
};
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
});
I need to check whether the draft object is empty, and output the save successfully information.
<span data-ng-hide="draft == {}" style="color:green">Your note has been saved.</span>
I have also tried:
<span data-ng-hide="draft.length == -1" style="color:green">Your note has been saved.</span>
or
<span data-ng-hide="draft == ''" style="color:green">Your note has been saved.</span>
But all of them are failed.
Add function isEmptyObject in your controller:
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.note = {};
$scope.notes = [];
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
$scope.isEmptyObject = function (obj) {
for (var i in obj) if (obj.hasOwnProperty(i)) return false;
return true;
};
});
Or you can use this function:
$scope.isEmptyObject = function (obj) {
return Object.keys(obj).length === 0;
}
HTML:
<span data-ng-hide="isEmptyObject(draft)" style="color:green">Your note has been saved.</span>
Please initialize null instead of empty object
$scope.draft = null;
And html should be
<span data-ng-hide="!draft" style="color:green">Your note has been saved.</span>
You can chek the condition inline in your span.
HTML:
<span data-ng-hide="Object.keys(draft).length === 0" style="color:green">Your note has been saved.</span>

Decorating a directive by adding a function that will call the directive's controller

I use a directive that is declared like this :
(function (directives) {
var FilterDirective = (function () {
function FilterDirective() {
var directive = {};
directive.restrict = 'A';
directive.scope = true;
directive.controller = elasticui.controllers.FilterController;
directive.link = function (scope, element, attrs, filterCtrl) {
scope.$watch(element.attr('eui-filter') + " | euiCached", function (val) { return scope.filter.filter = val; });
var enabled = false;
var enabledAttr = element.attr('eui-enabled');
if (enabledAttr) {
scope.$watch(enabledAttr, function (val) { return scope.filter.enabled = val; });
enabled = scope.$eval(enabledAttr);
}
scope.filter = {
filter: scope.$eval(element.attr('eui-filter') + " | euiCached"),
enabled: enabled
};
filterCtrl.init();
};
return directive;
}
return FilterDirective;
})();
directives.FilterDirective = FilterDirective;
directives.directives.directive('euiFilter', FilterDirective);
})
The controller of the directive is :
(function (controllers) {
var FilterController = (function () {
function FilterController($scope) {
this.scope = $scope;
}
FilterController.prototype.init = function () {
var _this = this;
if (this.scope.filter.filter) {
var isEnabled = this.scope.filters.contains(this.scope.filter.filter);
if (!isEnabled && this.scope.filter.enabled) {
this.scope.filters.add(this.scope.filter.filter);
isEnabled = true;
}
}
this.scope.filter.enabled = isEnabled;
this.scope.$watch('filter.enabled', function (newVal, oldVal) {
if (newVal !== oldVal) {
_this.updateFilter();
}
});
this.scope.$watch('filter.filter', function (newVal, oldVal) {
if (!elasticui.util.EjsTool.equals(oldVal, newVal)) {
if (oldVal) {
_this.scope.filters.remove(oldVal);
}
_this.updateFilter();
}
});
};
FilterController.prototype.updateFilter = function () {
if (!this.scope.filter.filter) {
return;
}
if (this.scope.filter.enabled) {
this.scope.filters.add(this.scope.filter.filter);
}
else {
this.scope.filters.remove(this.scope.filter.filter);
}
};
FilterController.$inject = ['$scope'];
return FilterController;
})();
controllers.FilterController = FilterController;
})
Actually, the directive has a scope containing a filter object which contains two attributes filter : { enabled : boolean, filter : object} and the directive is used like this :
<label class="btn" ng-model="filter.enabled"
eui-filter="ejs.TermFilter('field','value')" btn-checkbox>
when the button is clicked the filter.enabled is set. My purpose is to add a behavior that will permit to change filter.enabled value via a function external to the directive.
The directive will look like this :
<label class="btn" ng-model="filter.enabled"
eui-filter="ejs.TermFilter('field','value')" eui-enable-fn="fn(somevariable)" btn-checkbox>
where fn will take the somevariable and set it to the filter.enabled.
Thanks in advance,
If you want to enable/disable a filter through the pressure of a button why not declare a filter with the property eui-enabled set to a custom toggling variable?
In other words it would result as:
HTML:
<label class="btn" eui-filter="..." eui-enabled="my_toggling_variable">
<button type=button ng-click="toggleVar()"></button>
JS:
myApp.controller('myCtrl', ['$scope', function($scope) {
$scope.my_toggling_variable = false;
$scope. toggleVar = function(){
$scope.my_toggling_variable = !$scope.my_toggling_variable;
};
}]);
Hope to have understood well the topic.

Resources