"[object object]" shown when double-clicking input - html

Below is the template I am using for the directive. In code we are
fetching the data from a service in that data we have all the
information of that particular person. And from that data we are
showing only first name, last name and designtion or company
affiliation.
<div ng-if="model" class="entry-added">
<span class="form-control"><b>{{model.fullName}}</b>, <br/><span class="small-font">{{(model.designation)?model.designation:model.companyAffiliation}}</span></span>
<a ng-click="removePerson()" class="action-remove"><i class="fa fa-remove"></i></a>
</div>
<div ng-show="!model" class="input-group">
<input type="text"
class="form-control"
name="{{name}}"
id="{{name}}"
placeholder="{{placeholder}}"
ng-required="{{isRequired}}"
typeahead-on-select = "change($item, $model, $label)"
ng-model="model"
typeahead-min-length="3",
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
typeahead-template-url="typeAheadTemplate.html"
typeahead-loading="searching"
typeahead-editable="false">
<script type="text/ng-template" id="typeAheadTemplate.html">
<a class="ui-corner-all dropdown" tabindex="-1">
<div class="col-md-2"><img class="dropdown-image" ng-src="https://people.***.com/Photos?empno={{match.model.employeeNumber}}"></div>
<div>
<div bind-html-unsafe="match.model.fullName"></div>
<div bind-html-unsafe="match.model.designation"></div>
</div>
</a>
</script>
I am using a custom directive to display a search field. The drop down is displaying [object object].
Directive
// In backend taxDeptContact is a Person type object
/*
Directive code
*/
(function () {
'use strict';
angular.module('treasuryApp.directives').directive('employeeSearch', employeeSearch);
employeeSearch.$inject = ['$resource', '$rootScope', 'ErrorHandler'];
function employeeSearch($resource, $rootScope, ErrorHandler) {
return {
restrict: 'E',
require: '^form',
scope: {
model: "=",
isRequired: '#',
submitted: "=",
onSelect: '&',
name: '#',
index:'#'
},
link: function(scope, el, attrs, formCtrl) {
//set required attribute for dynamically changing validations
scope.searchEmployees = function (searchTerm) {
var users = [];
var myResult = [];
var result = $resource($rootScope.REST_URL + "/user/getEmployees", {term: searchTerm}).query().$promise.then(function (value) {
//console.log(value)
$.each(value, function(i, o) {
users.push(o);
});
return users;
});
return result;
}
scope.removePerson = function() {
scope.model=null;
}
scope.userNotSelectedFromTypeahead = function(name) {
if(undefined === formCtrl[name]) {
return false;
}
return formCtrl[name].$error.editable;
};
scope.change = function(item, model, label) {
scope.model = item
scope.onSelect(
{name: scope.name, person: scope.model});
},
templateUrl: 'app/components/common/directives/employee-search.tpl.html'
};
}
})();
View that is using the directive
<div class="form-group">
<label class="col-sm-3>Tax Dept Contact</label>
<div class="col-sm-4">
<employee-search model="reqCtrl.requestObj.taxDepartmentContact" name="taxDeptContact" is-required="false" submitted="reqCtrl.submitted"/>
</div>
</div>
Image of the error occuring

Looks like this may be your trouble spot
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
suggestion for suggestion is pulling the whole object. Have you tried displaying a particular attribute of suggestion?
For example: if you had a suggestion.name attribute you would write:
typeahead="suggestion.name for suggestion in searchEmployees($viewValue)"

Finally got the answer: I used autocomplete="off" in my directive and thats all
<input type="text" autocomplete="off" />

Related

AngularJS, how to display contents of a received JSON object

I have successfully received the JSON object from an API, which is evident from a console.log code. Now, I want to display the various elements in that JSON file. For example, the JSON contains elements like "name" and "url". How do I display these individually, in an h1 HTML element, after clicking the submit button and fetching the JSON file. I'm a newbie and sorry if this is an obvious question, I'm kinda stuck and need help. Thank you in advance!
My HTML Code is:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{response.data.name}}
</body>
The JS is:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($scope, $http) {
var id = "my secret key comes here";
$scope.formData = {};
$scope.searchText;
$scope.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + $scope.formData.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name)
})
}
});
Thank you so much in advance!
You need to use a variable to assign it with the response data and then use it in html. For example to display name from response.data.name:
<body ng-app="myApp">
<div ng-controller="UserCtrl as vm">
Search : <input type="text" placeholder="Search Employees"
ng-model="vm.searchText"/> <br/><br/>
<button ng-click="vm.getByID()">Submit</button>
<h1>{{ vm.name }}</h1>
</body>
In controller:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($http) {
let vm = this;
var id = "my secret key comes here";
vm.searchText;
vm.name;
vm.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + vm.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name);
vm.name = response.data.name;
})
}
});
Put the data on $scope:
$scope.getByID = function() {
var url = "https://rest.bandsintown.com/artists/" + $scope.formData.searchText;
var params = { app_id: id };
var config = { params: params };
$http.get(url, config)
.then(response => {
console.log(response.data.name)
$scope.data = response.data;
})
}
Then use the ng-repeat directive:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{data.name}}<br>
<div ng-repeat="(key, value) in data">
{{key}}: {{value}}
</div>
</div>
</body>
For more information, see
AngularJS ng-repeat Directive API Reference

Vuejs component does not render immediately

I have a vue app and a component. The app simply takes input and changes a name displayed below, and when someone changes the name, the previous name is saved in an array. I have a custom component to display the different list items. However, the component list items do not render immediately. Instead, the component otems render as soon as I type a letter into the input. What gives? Why would this not render the list items immediately?
(function(){
var app = new Vue({
el: '#app',
components: ['name-list-item'],
data: {
input: '',
person: undefined,
previousNames: ['Ian Smith', 'Adam Smith', 'Felicia Jones']
},
computed: {
politePerson: function(){
if(!this.person) {
return 'Input name here';
}
return "Hello! To The Venerable " + this.person +", Esq."
}
},
methods: {
saveInput: function(event){
event.preventDefault();
if(this.person && this.previousNames.indexOf(this.person) === -1) {
this.previousNames.push(this.person);
}
this.setPerson(this.input);
this.clearInput();
},
returnKey: function(key) {
return (key + 1) + ". ";
},
clearInput: function() {
this.input = '';
},
setPerson: function(person) {
this.person = person;
}
}
});
Vue.component('name-list-item', {
props: ['theKey', 'theValue'],
template: '<span>{{theKey}} {{theValue}}</span>'
});
})()
And here is my HTML.
<div id="app">
<div class="panel-one">
<span>Enter your name:</span>
<form v-on:submit="saveInput">
<input v-model="input"/>
<button #click="saveInput">Save</button>
</form>
<h1>{{politePerson}}</h1>
</div>
<div class="panel-two">
<h3>Previous Names</h3>
<div>
<div v-for="person, key in previousNames" #click='setPerson(person)'><name-list-item v-bind:the-key="key" v-bind:the-value="person" /></div>
</div>
</div>
</div>
You are not defining your component until after you have instantiated your Vue, so it doesn't apply the component until the first update.

Unable to access $scope model

In my main html, I have a view which loads templates.
<div data-ng-view></div>
It loads a html whenever the link is clicked.
app.config(["$routeProvider", function ($routeProvider) {
'use strict';
$routeProvider
.when("/", {
templateUrl: "events.html"
});
}]);
On this page (template) , I have a directive which loads another html file
app.directive('ngPost', function () {
'use strict';
return {
restrict: 'A',
templateUrl: 'postbox.html'
};
});
I then use this directive on my events.html page by using <div data-ng-Post></div>
In postbox, I have two input fields and a button
<input type="text" id="user" data-ng-model="username" />
<input type="text" id="mess" data-ng-model="message"/>
<button data-ng-click="Add(eventid-1, username, message)">Post</button>
Upon clicking the button, I have some operations, then I try to clear the input fields, but I cannot. Method here :
$scope.Add = function (index, uname, msg) {
var a = {user: uname, message: msg, time: new Date()};
$scope.data[index].messages.push(a);
$scope.message = ''; // clearing here
$scope.username ='';
};
The clearing does not happen, I do not know why. My controller that has this Add method wraps the <div data-ng-view></div>in the main html file so it is the outermost controller and should have access to all $scope models inside. Why does it not work?
Note that the operations before the clearing works with no problems
Your add method is in the parent scope. The parent's scope cannot see it's children, it works the other way around. The message and username properties are defined in the directive's child scope. From a child you can reference parent properties, but not the other way around.
If you add scope: false and transclude: false to your directive, it won't create it's own scope and instead use its parent's scope, so your directive would look something like this:
angular.module('app', []).controller("myController",myController);
function myController($scope){
var ctrl = this;
ctrl.hello ="Hello"
};
angular.module('app').directive("childThing", function() {
return {
template: '<div>{{message}}</div><div>{{username}}</div>',
scope: false,
transclude: false,
controller: function($scope) {
$scope.username="Mike Feltman"
$scope.message="Hi Mike"
}
}
})
and you can access the elements that the directive adds to the scope from the parent like this:
<div ng-controller="myController as ctrl">
{{username}} in the parent.
<div>{{ctrl.hello}}</div>
<child-thing></child-thing>
</div>
Update using your template:
{{username}} in the parent.
{{ctrl.hello}}
Javascript:
function myController($scope){
var ctrl = this;
ctrl.hello ="Hello"
$scope.add = function() {
alert($scope.username)
}
};
angular.module('app').directive("childThing", function() {
return {
template: '<input type="text" id="user" data-ng-model="username" /><input type="text" id="mess" data-ng-model="message"/>',
scope: false,
transclude: false,
}
})

angularjs: Better way to use ngModel.$asynValidators

I just want to asked if there's a better way to improve my user validation codes.
directive.js
angular.module('installApp')
.directive('usernameValidator', function ($q, $timeout, $http) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.username = function(modelValue, viewValue) {
return $http.post('../api/v1/checkUsers', {user: {'username':viewValue}}).then(
function(response){
scope.checkUsers = response.data;
var deferred = $q.defer();
$timeout(function() {
if(scope.checkUsers['status'] == 404){
deferred.reject();
}else{
deferred.resolve();
}
}, 2000);
return deferred.promise;
});
};
}
}
});
accounts.html
<form name="myForm" ng-submit="submit()">
<div>
<label>Username: <input type="text" ng-model="signup.username" name="username" required username-validator>
</label>
<div ng-if="myForm.username.$dirty">
<div ng-messages="myForm.username.$error" class="validation-error">
<div ng-message="required">Username required</div>
<div ng-message="username">Username already in use</div>
</div>
<div ng-messages="myForm.username.$pending" class="validation-pending">
<div ng-message="username">Checking username availability... </div>
</div>
</div>
</div>
<div>
<label>Password: <input type="password" ng-model="signup.password" name="password" required></label>
<div ng-messages="myForm.password.$error" ng-if="myForm.password.$dirty" class="validation-error">
<div ng-message="required">Password required</div>
</div>
</div>
<button type="submit" ng-disabled="myForm.$invalid || myForm.$pending">Submit</button>
</form>
The above code is perfectly working fine, but there is a doubt in my mind on how can I improve it in a better way. I've seen many examples and I noticed they didn't used mostly the if/ else condition. Please help
One thing you could do is try to make your directive reusable.
A good example I found on the internet is coming from Year of moo
angular
.module('yourmodule')
.directive('recordAvailabilityValidator',
['$http', function($http) {
return {
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
var apiUrl = attrs.recordAvailabilityValidator;
function setAsLoading(bool) {
ngModel.$setValidity('recordLoading', !bool);
}
function setAsAvailable(bool) {
ngModel.$setValidity('recordAvailable', bool);
}
ngModel.$parsers.push(function(value) {
if(!value || value.length == 0) return;
setAsLoading(true);
setAsAvailable(false);
$http.get(apiUrl, { v : value })
.success(function() {
setAsLoading(false);
setAsAvailable(true);
})
.error(function() {
setAsLoading(false);
setAsAvailable(false);
});
return value;
})
}
}
}]);

angular working on plunker but not work on browser or emulator

i have created ionic project with slidemenu. I also created custom reusable directive where I am getting data from rest api and assigning its value to directive for ng-repeat, it is like dropdown but it items open in modal popup. So when I select value from first directive,I will filter another rest api to assign data to same directive for another instance.
In that I have input box act as filter which filter for ng-repeat items
Now issue starts in first directive filter works very good but second directive filter will not work. When I filter than all items will get clear and I remove value from input box than still items will not appear back.
First I thought that my first directive json object is 1 level that is the reason it is working and second directive json is nested object.
So I created plunker with same exact code which works like charm but it does not work on desktop or emulator.
can somebody tell me what can be the issue. I am not putting plunker link as it working very good, so it is worthless
Directive code
angular.module('plexusSelect', []).directive('plexusSelect', ['$ionicModal',
function($ionicModal) {
// Runs during compile
return {
scope: {
'items': '=',
'text': '#',
'textIcon': '#',
'headerText': '#',
'textField': '#',
'textField2': '#',
'valueField': '#',
'callback': '&'
},
require: 'ngModel',
restrict: 'E',
templateUrl: 'templates/plexusSelect.html',
link: function($scope, iElm, iAttrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
$scope.allowEmpty = iAttrs.allowEmpty === 'false' ? false : true;
$scope.defaultText = $scope.text || '';
$ionicModal.fromTemplateUrl('plexusSelectItems.html', {
'scope': $scope
}).then(function(modal) {
$scope.modal = modal;
$scope.modal['backdropClickToClose'] = false;
});
$scope.showItems = function($event) {
$event.preventDefault();
$scope.modal.show();
}
$scope.hideItems = function() {
$scope.modal.hide();
}
/* Destroy modal */
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
$scope.viewModel = {};
$scope.clearSearch = function() {
$scope.viewModel.search = '';
}
/* Get field name and evaluate */
$scope.getItemName = function(field, item) {
return $scope.$eval(field, item);
}
$scope.validateSingle = function(item) {
$scope.text = $scope.$eval($scope.textField, item) + ($scope.textField2 !== undefined ? " (" + $scope.$eval($scope.textField2, item) + ")" : "");
$scope.value = $scope.$eval($scope.valueField, item);
$scope.hideItems();
if (typeof $scope.callback == 'function') {
$scope.callback($scope.value);
}
ngModel.$setViewValue($scope.value);
}
$scope.$watch('text', function(value) {
if ($scope.defaultText === value) $scope.placeholder = 'placeholderGray';
else $scope.placeholder = 'placeholderBlack';
});
}
};
}
])
Directive html
<ion-list>
<ion-item class="item-text-wrap item" ng-click="showItems($event)">
<a class="item-icon-left item-icon-right">
<i class="icon {{textIcon}} placeholderGray"></i>
<span class="{{placeholder}}">{{text}}</span>
<i class="icon ion-chevron-right"></i>
</a>
</ion-item>
</ion-list>
<script type="text/ng-template" id="plexusSelectItems.html">
<ion-view class="select-items modal">
<ion-header-bar class="bar-positive" has-subheader="true">
<button ng-click="hideItems()" class="button button-positive button-icon ion-ios7-arrow-back"></button>
<h1 class="title">{{headerText}}</h1>
</ion-header-bar>
<ion-header-bar class="bar-light bar-subheader bar bar-header item-input-inset">
<div class="item-input-wrapper">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" ng-model="viewModel.search" placeholder="select city...">
<button ng-show="viewModel.search.length" ng-click="clearSearch()" class="customIcon button button-icon ion-close-circled input-button"></button>
</div>
</ion-header-bar>
<ion-content>
<div class="list">
<label ng-repeat="item in items | filter:viewModel.search" class="item item-text-wrap" ng-click='validateSingle(item)'>
{{getItemName(textField, item)}} {{textField2 !== undefined ? " (" + getItemName(textField2, item) + ")" : ""}}
</label>
</div>
</ion-content>
</ion-view>
</script>
My Controller
.controller('SearchCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get("http://xxxx/lists/getbytitle('xxx')/items?$select=City_Code,City_Name_EN&$filter=Active eq 1&$orderby=City_Name_EN asc", {
headers: {
Accept: "application/json;odata=verbose"
}
}).then(function(resp) {
$scope.deptStations = resp.data.d.results;
}, function(err) {
console.log(err);
});
$scope.deptStation = {
value: null
};
$scope.arrStation = {
value: null
};
$scope.$watch('deptStation.value', function(deptStation) {
$http.get("http://xxx/lists/getbytitle('xxx')/items?$select=Destination/City_Code,Destination/City_Name_EN&$expand=Destination/City_Code,Destination/City_Name_EN&$filter=Origin/City_Code eq '" + deptStation + "'&$orderby=Destination/City_Name_EN asc", {
headers: {
Accept: "application/json;odata=verbose"
}
}).then(function(resp) {
$scope.arrStations = resp.data.d.results;
}, function(err) {
console.log(err);
});
});
}
]);
My First Directive JSON
{"d":{"results":[{"City_Name_EN":"Abu Dhabi","City_Code":"AUH"},{"City_Name_EN":"Alexandria","City_Code":"HBE"},{"City_Name_EN":"Amman","City_Code":"AMM"},{"City_Name_EN":"Bahrain","City_Code":"BAH"},{"City_Name_EN":"Bangkok","City_Code":"BKK"}]}}
My Second Directive JSON
{"d":{"results":[{"Destination":{"City_Code":"HBE","City_Name_EN":"Alexandria"}},{"Destination":{"City_Code":"BKK","City_Name_EN":"Bangkok"}},{"Destination":{"City_Code":"MAA","City_Name_EN":"Chennai"}},{"Destination":{"City_Code":"COK","City_Name_EN":"Cochin"}}]}}
Really I hate this but it turnout to be a bug in new version.
On plunkr I was referencing 1.0.0-beta.1 ionic.bundle.min.js
And in my project I was referencing latest version which is 1.0.0-beta.14 ionic.bundle.min.js
Once I replace same version js file of my project to plunkr reference, it start behaving same as it is on my project.