How to set value of span within an Ng-repeat - javascript

I am using an ng-repeat in order to list the contents of my data model where the content is being displayed correctly. However, as I am creating a contacts application, I am utilising a circle shape with text inside of it to display the first character from the first name and the first character from the last name, of each contact in the list - my code for this can be seen below:
HTML:
<ul class="collection" ng-show="customers.length">
<li class="collection-item avatar" ng-click="showUserDetail(customer.id)" ng-repeat="customer in customers | orderBy: 'first_name' | filter: searchText" ng-class="{'active': customer.id == selectedUser.id}">
<span ng-init="setContactCircle(customer.first_name,customer.last_name)" id="contact-info" class="contact-circle">TC</span>
<span class="title">{{customer.first_name}} {{customer.last_name}}</span>
<p>{{customer.email}}
<br> {{customer.mobile_number}}
</p>
</li>
</ul>
JS:
$scope.setContactCircle = function(first_name,last_name) {
var strFirst = first_name.charAt(0);
var strLast = last_name.charAt(0);
var strName = strFirst + strLast;
/* span = document.getElementById("contact-info");
txt = document.createTextNode(strName);
span.innerHTML = txt.textContent; */
//document.getElementById("contact-info").innerHTML = strName;
$("#contact-info").text(strName);
console.log(strName);
}
The ng-init appears to be working as the first character from the first name and the first character from the last name are being outputted to the console in 'console.log(strName);' but the text is not being set on the span class.
EDIT
Thank you all for your help where the below has resolved the issue.
HTML:
<span ng-bind="setContactCircle(customer)" id="contact-info" class="contact-circle"></span>
JS:
$scope.setContactCircle = function(customer) {
var strFirst = customer.first_name.charAt(0);
var strLast = customer.last_name.charAt(0);
return strFirst + strLast;
}

Manupulating DOM elements from your controller is a bad Angular design. Instead of using $("#contact-info").text you can user angular data binding.

You are mixing jquery and angular. Both are attempting to manipulate the DOM and they don't typically play nice together.
Could you please try -
<span ng-bind="setContactCircle(customer)" id="contact-info" class="contact-circle"></span>
$scope.setContactCircle = function(first_name,last_name) {
var strFirst = first_name.charAt(0);
var strLast = last_name.charAt(0);
return strFirst + strLast;
}

HTML:
<ul class="collection" ng-show="customers.length">
<li class="collection-item avatar" ng-click="showUserDetail(customer.id)" ng-repeat="customer in customers | orderBy: 'first_name' | filter: searchText" ng-class="{'active': customer.id == selectedUser.id}">
<span ng-init="setContactCircle(customer)" id="contact-info" class="contact-circle">customer.circle</span>
<span class="title">{{customer.first_name}} {{customer.last_name}}</span>
<p>{{customer.email}}
<br> {{customer.mobile_number}}
</p>
</li>
</ul>
JS:
$scope.setContactCircle = function(customer) {
customer.circle = customer.first_name.charAt(0) + customer.last_name.charAt(0);
}

Related

ng-checked not working for multiple condition expression in angular js template

I want to check the Users check box on selection of category. But when there is no key for Category in usr_cat array previously checked check boxes not unchecked. I want to uncheck all the users when Manager is selected in the category.
Category = [{cid:'1',name:'Head'},cid:'2',name:'Manager'}]
users = [0:{'id':10,name:'AAAAA'},{'id':12,name:'BBBBB'},{'id':13,name:'CCCCC'},{'id':14,name:'DDDDDDDD'}]
usr_cat = ['1':[10,14]]
Category List
<ul class="list-unstyled cat-lst">
<li ng-repeat = "cat in categery" ng-click ="selectcategry(cat.cid)>{{cat.name}} </li>
<ul>
User List
<ul class="list-unstyled usr-lst">
<li ng-repeat = "usr in users">
<span class=" checkbox ">
<input class="optionChechk " id="user_{{usr.id}}" type="checkbox" ng-checked = "{{usr_cat[sele_cid] != 'null' && usr_cat[sele_cid] != 'undefined' && usr_cat[sele_cid] != '' && (usr_cat[sele_cid].indexOf(usr.id) != -1)}}" ng-value="{{usr.id}}" >
<label for="user_{{usr.id}}" txt = "{{usr_cat[sele_cid]}}">{{usr.name}}</label>
</span>
<li>
</ul>
JS
$scope.selectcategry = function(cid){
$sele_cid = cid;
}
Hi the code contains many error
Angular braces are used inside ng-attributes.
improper closer of quotes"".
Improper naming standards camel-casing is the format.
Category is the variable you mentioned spelling categery is used
everywhere.
<ul class="">
<li ng-repeat = "cat in categery"
ng-click ="selectcategry(cat.cid)">{{cat.name}}</li>
</ul>
Array responses are seem to inValid,suggested bellow,scope is missing in sele_cid
$scope.categery =[{"cid":'1',"name":'Head'},{"cid":'2',"name":'Manager'}];
$scope.users = [{'id':10,"name":'AAAAA'},{'id':12,"name":'BBBBB'}, {'id':13,"name":'CCCCC'},{'id':14,"name":'DDDDDDDD'}];
$scope.usr_cat = [10,14];
$scope.selectcategry = function(cid){
$scope.sele_cid = cid;
}
please work on this

Retreiving filteredItems from uib-typeahead custom popup doesn't work

Retreiving filteredItems from ng-repeat in controller through $scope doesn't work
I am trying to get filtered items from ng-repeat but I get undefined when console logging the value of $scope.filteredItems. I even tried the solution provided in Can't get the filtered items from my filtered list inside a modal but it didn't work either.
The ng-repeat is in a uib-typeahead custom popup templates for typeahead's dropdown. I am trying to get the filtered value in the parent controller.
example-input.component.ts
/////////////////////////////////
componentController.$inject = ['$scope', 'exampleDataService'];
function componentController($scope, exampleDataService) {
var someInput = this;
someInput.typedText = '';
someInput.onKeyPress = onKeyPress;
return;
/////////////////////////////////
//controller implementation detail
/////////////////////////////////
function onKeyPress(){
console.log($scope.filteredItems); // prints undefined
}
}
UIB-Typeahead Custom Template for Popup
<script type="text/ng-template" id="input-custom-template.html">
<ul class='dropdown-menu' ng-show='isOpen() && !moveInProgress'
ng-style="{top: position().top+'px', left: position().left+'px'}"
role='listbox' aria-hidden='{{!isOpen()}}' match-limit in-view-container>
<li style="max-height:0;overflow:hidden"><span in-view="$inview && matchLimit.reset()"> </span></li>
<li ng-repeat='match in (filteredItems = (matches | someMatchSort:query | limitTo:matchLimit.value)) track by some.model.example '
ng-class='{active: isActive($index) }'
ng-mouseenter='selectActive($index)'
ng-click='selectMatch($index, $event)'
role='option' id='{{::match.id}}'
in-view="!$inview && isActive($index) && scrollTarget.scrollIntoView()"
scroll-target
>
<div uib-typeahead-match index='$index' match='match'
query='query' template-url='templateUrl'>
</div>
</li>
</ul>
</script>
<input type="text" ng-model="someInput.typedText" typeahead-min-length="1"
uib-typeahead="option.example as option.value for option in someInput.options | filter:{value:$viewValue}"
class="form-control input-text-example icon-search"
placeholder="example"
typeahead-popup-template-url="input-custom-template.html"
ng-keypress="someInput.onKeyPress()"/>
If you need any additional info pls let me know. There is also a filter called someMatchSort.filter.ts but I'm not sure if it makes difference to add it here. Anyways let me know, I will update my question
You might want to use ng-keyup in your case.
Then in your component write like so
function onKeyPress(){
console.log($scope.$$childHead.matches.length);
}

How to get element by id which is dynamically created by ng-repeat in angularjs

I am only posting the necessary code and solving this much will clear rest of my doubts. I am new to angularjs, so kindly forgive if I am asking something stupid.
I am using ng-repeat to generate a list which uses an array defined in the controller scope. When I click on 'Add Another' button, a new element is created. I want to get access of this element to add a class to it. But when I use 'getElementById' function in the same function 'addNewForm' I get 'null'.
However, when I call function 'fn' by hitting 'Find Untitled' button, I get the correct element. Could anybody explain and solve this? Any help is appreciated. Thanks in advance!
I am posting the code below:
HTML:
<div ng-controller="myctrl3">
<ul id ="menu_Ul">
<li ng-repeat="x in list">
<button id="{{ 'navAppsButtonID-' + $index }}">{{x}}</button>
<br>
</li>
<li>
<button ng-click="addNewForm()">Add another</button>
</li>
</ul>
<button ng-click="fn()">Find Untitled</button>
</div>
JS:
.controller("myctrl3", function($scope) {
var list = ['abcd', 'efgh', 'ijkl', 'mnop'];
$scope.list = list;
$scope.abc = function () {
var listPush = function () {
$scope.list.push("Untitled Menu");
for(var i = 0;i<$scope.list.length-1;i++) {
var element = document.getElementById('navAppsButtonID-'+i);
element.classList.remove('current');
}
};
var listLen = $scope.list.length;
if($scope.list[listLen-1] === undefined) {
listPush();
}
else if ($scope.list[listLen-1] == "Untitled Menu") {
alert("Cannot open more than one Untitled Menu at the same time.");
}
else {
listPush();
}
};
$scope.addNewForm = function() {
$scope.abc();
console.log("Element is: ", document.getElementById('navAppsButtonID-'+($scope.list.length-1)));
};
$scope.fn = function () {
console.log("Element is: ", document.getElementById('navAppsButtonID-'+($scope.list.length-1)));
};
})
You're thinking too much jQuery and too little angular. If the goal is to add a class to the last element of ng-repeat, this is how you do that:
<li ng-repeat="x in list">
<button ng-class="{ current: $last }">{{ x }}</button>
</li>
$last is a variable available inside ng-repeat, and if it's true, ng-class will set the class current on the element.
You don't assign unique ids to elements to getElementById from somewhere else when working in angular.

$scope.apply not working in Angular

im trying to learn Angular.
Here is what im trying to do:
I am building an App that shows me citys. When i click on a city i want to see a list of all my favourite citys.
Using an "Show-List" Button with ng-click works but requires the button the be pushed.
Here is my approach for getting it done automatic:
I want a list in my DOM automatically updated on change of the list.
$scope.$watch('updatedList', function() {
// CHECK IF WORKS
console.log($scope.updatedList);
// APPLY TO DOM
$timeout(function(){
$scope.$apply(function () {
$scope.watchList = $scope.updatedList;
});
}, 1000)
});
The Console shows no error and gives out the correc values:
Object {city.3: "Herat", city.7: "Haag", city.10: "Tilburg" ......}
In my div is the following:
<ul>
<li ng-repeat="y in updatedList">{{ y }}</li>
</ul>
<ul>
<li ng-repeat="a in watchList">{{ a }}</li>
</ul>
First for the NG-Click-Version(which works on click) second for the $scope.$watch
Sorry for lots of questions but im really struggling with the Angular-Docs.
EDIT:
Function that Adds Citys to the List:
$scope.addToList = function(name,id) {
var cityToAdd = name;
var cityToAddID = id;
// ADD A CITY TO THE COOKIE -> WORKS
$cookies.put('city.' + cityToAddID, cityToAdd);
$scope.newList = $cookies.getAll();
$scope.addToListMessage = cityToAdd + " wurde hinzugefĆ¼gt";
// Show short INFONOTICE
window.setTimeout(function() {
$scope.$apply(function() {
$scope.addToListMessage = "";
});
}, 1000);
// Update the List
$scope.updateList();
};
Second Functions -> gets Values from Cookies and puts them to an Array:
$scope.updateList = function() {
var allCitys = $cookies.getAll();
// PUT ALL INTO AN ARRAY -> WORKS
var favouritesFromCookie = [];
$.each(allCitys, function(index, value) {
if (index.indexOf('city.') == 0) { favouritesFromCookie.push(value) }
});
// PUT THE ARRAY OF CITYS INTO A SCOPE_VARIABLE
$scope.updatedList = favouritesFromCookie;
};
Your $scope.updatedList needs to be an array to be used in ng-repeat.
You shouldn't directly write a list in expression. Try this
<ul>
<li ng-repeat="y in watchList">{{ y.city }}</li>
<li ng-repeat="y in watchList">{{ y.yourListItem}}</li>
</ul>

Doesn't work two ways of filtering (AngularJS)

I'm trying to make two ways of filtering (via clicking on letters or via typing in input field).
<body ng-controller="MainController">
<ul search-list=".letter" model="search">
<li class="letter" ng-repeat="letter in alphabet.letter">{{ letter }}</li>
</ul>
<div class="container" ng-controller="CountriesController">
<input id="q" type="text" ng-model="search " />
<ul>
<li ng-repeat="country in countries.country | filter:search:startsWith">{{ country }}</li>
</ul>
</div>
</body>
and js:
var app = angular.module('demo', []);
var controllers = {};
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
app.directive('searchList', function() {
return {
scope: {
searchModel: '=model'
},
link: function(scope, element, attrs) {
element.on('click', attrs.searchList, function() {
scope.searchModel = $(this).text();
scope.$apply();
});
}
};
});
controllers.MainController = function($scope) {
$scope.setTerm = function(letter) {
$scope.search = letter;
};
$scope.alphabet = {
letter: alphabet
}
};
controllers.CountriesController = function($scope){
$scope.countries = {
country:['Ukraine','Urugvai','Russia','Romania','Rome','Argentina','Britain']
}
$scope.startsWith = function (actual, expected) {
var lowerStr = (actual + "").toLowerCase();
return lowerStr.indexOf(expected.toLowerCase()) === 0;
}
};
app.controller(controllers);
On first look everything is working fine, but it is so only on first look...
When at first I click on any letter - filter works good.
When then I'm typing in input field - filter works good.
But after I typed in input field or delete text from there via 'backspace' button - filter by clicking on letters stops working...
Why it works like this and how I can fix this issue?
Here is my DEMO
Thanx in advance!
The problem fount for using two controler's. If you remove CountriesController , then everything working good.
The Search values was confused with which controller using that scope object.I think you don't need implement two controller for this scenario
See the working demo if you remove CountriesController.
change this part of html to this it works fine (ng-model="$parent.search ")
<div class="container" ng-controller="CountriesController">
<input id="q" type="text" ng-model="$parent.search " />
<ul>
<li ng-repeat="country in countries.country | filter:search:startsWith">{{ country }}</li>
</ul>
</div>

Categories

Resources