how to print alphabets for numbering using ng-repeat - html

I want to print alphabets for marking options of questions using ng-repeat directive in Angular.
<div ng-repeat="options in $root.options">
//print alphabets in sequence here//:{{options}}
</div>
$root.options have 4 option, now i want it to be printed like
A: option 1
B: option 2
C: option 3
D: option 4
PS: I am not using HTML list neither I am planning to.

One solution would be to create a string in your $scope as follows:
$scope.alphabet = 'abcdefghijklmnopqrstuvwxyz';
You can then use track by $index in your ng-repeat to access letters from the string as follows:
<div ng-repeat="options in $root.options track by $index">
{{ alphabet[$index] }}: {{ options }}
</div>

Here you go:
First define all the alphabets:
$scope.letterArray = [];
for(var i = 0; i < 26; i++) {
$scope.letterArray.push(String.fromCharCode(65 + i));
}
And then use it:
<div ng-repeat="options in $root.options">
{{letterArray[$index]}}: option {{$option}}
</div>
See it working below:
var myApp = angular.module("sa", []);
myApp.controller("foo", function($scope) {
$scope.letterArray = [];
for (var i = 0; i < 26; i++) {
$scope.letterArray.push(String.fromCharCode(65 + i));
}
$scope.options = [{
name: "hello foo"
}, {
name: "hello bar"
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sa" ng-controller="foo">
<div ng-repeat="option in options">
{{letterArray[$index]}}: {{option.name}} {{$index}}
</div>
</div>

Related

Angular.js string to html

Hello I want to bind html to div . Code below I wrote like that
.controller('HomeCtrl',['$http','$scope','$state',function($http,$scope,$state){
$scope.data = {};
$scope.userInfo = function() {
$state.go('user');
}
var user=JSON.parse(sessionStorage.user);
$scope.user=user.name+ ' ' + user.surname;
$http.get('http://example:3000/projects').success(function(response){ //make a get request to mock json file.
var data=response;
var text='';
for (var i=0;i<data.length;i++) {
text+='<a id="task_'+data[i]._id+'" class="item item-icon-left task_'+data[i]._id+'" ng-click="getProject('+data[i]._id+')">';
text+='<i class="icon ion-android-folder-open"></i> '+data[i].name;
text+='</a>';
}
console.log(text);
$scope.tasks=text;
})
.error(function(err){
alert("hata");
})
}])
in console.writeline string seems correctly but in html ngclick and id attributes aren't shown .
<div ng-bind-html="tasks">
</div>
in html i wrote above . Where do I make mistake ?
Thanks in advance ...
You will use ng-repeat ;
in html
<a class="item item-icon-left" ng-repeat="item in projects" ng-click="getProject({{item.id}},'{{item.name}}')">
<i class="icon ion-android-folder-open"></i> {{item.name}}
</a>
put this and in controller.js put the data in array below
$http.get('http://example:3000/projects').success(function(response){ //make a get request to mock json file.
var data=response;
var text='';
var projects=[];
for (var i=0;i<data.length;i++) {
var item={
id:data[i]._id,
name:data[i].name
}
projects.push(item);
}
console.log(projects);
$scope.projects=projects;
})
.error(function(err){
alert("hata");
})

clone object with unique name in Angular

I'm new to Angular and looking for a way to make a clone button inside a list.
When I click this button, it will clone the object and add a number to the object name:
"new test" - will be changed to "new test (2)" and so on...
It requires to check the last 3 letters every time and check all the objects every time.
Is there any library doing this?
I think you don't need any lib for this. Basically, it you need one loop that looks for duplicates. See an example:
angular.module('myApp', [])
.controller('MyCtrl', function($scope){
$scope.items = ['Sample item'];
$scope.suggestedNewName = 'Sample item';
var isNameOccupied = function(name) {
return $scope.items.indexOf(name) >= 0;
};
$scope.addNewItem = function(){
var suggestedName = $scope.suggestedNewName;
var newName = suggestedName;
for (var i = 2; isNameOccupied(newName); i++) {
newName = suggestedName + " (" + i + ")";
}
$scope.items.push(newName);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<form ng-controller="MyCtrl" ng-submit="addNewItem()">
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
<label>Suggested name for new item:</label>
<input type="text" ng-model="suggestedNewName">
<button type="submit">Add new item!</button>
</form>
</div>

Create div with AngularJS

I know it is very simple but I wanna ask how to create div in ng-Repeat including an object proprty defines count of object.
For example i have an object like
function rowModel() {
this.id = 0;
this.columnCount = 1;
}
And I filled an array like below
$scope.Rows = [];
$scope.AddRow = function() {
var newRow = new rowModel();
newRow.id = 1;
newRow.columnCount = 3;
$scope.Rows.push(newRow);
}
I just wanna create an html template including 3 divs in each row.
This is my html and I wanna duplicate .cell div 3 times which is defined in object model
<button class="button" ng-click="AddRow()">Satır Ekle</button>
<div class="row cells{{row.columnCount}} bg-cyan" ng-repeat="row in Rows">
<div class="cell" ng-repeat="column in row.columnCount">{{row.id}}</div>
</div>
Anyone help?
Thanks
Use the following code in your controller
$scope.getNumber = function(num) {
return new Array(num);
}
And use the following in your view
<button class="button" ng-click="AddRow()">Satır Ekle</button>
<div class="row cells{{row.columnCount}} bg-cyan" ng-repeat="row in Rows">
<div class="cell" ng-repeat="column in getNumber(row.columnCount) track by $index">{{row.id}}</div>
</div>
Also if you do not want touch controller you can do this
ng-repeat="_ in ((_ = []) && (_.length=row.columnCount) && _) track by $index"
Here is the post where I found it.
i would create a filter for this
angular.module('myApp')
.filter('range', function(){
return function(n) {
var res = [];
for (var i = 0; i < n; i++) {
res.push(i);
}
return res;
};
});
After that, on the view is possible to use like this:
<div class="cell" ng-repeat="column in row.columnCount | range">{{row.id}}</div>

Update directive's template on controller's variable change - angularjs

What I'm trying to do is to get a JSON object from a $http request, requested inside a controller, and build a directive that displays the multiple objects in the JSON object in a grid.
The problem is that when the object arrives, I have to process it in the directive's controller to be able to use it in the template, as such, when the JSON object changes, it is not reflected in the template. How can I make the directive know about a change in the object and force it to reload the template?
// The Directive code
amobile.directive('grid', function() {
return {
restrict: 'E',
scope: {
break: '=break',
source: '=source'
},
controller: function($scope) {
var source = $scope.source;
$scope.final_data = new Array(source.length);
if(source){
for(var j=0; j < source.length; ++j){
var total = Math.ceil(source[j]['Division'].length / $scope.break);
var data = new Array(total);
for (var i = 0; i < total; ++i) {
data[i] = source[j]['Division'].slice(i * $scope.break, (i + 1) * $scope.break);
}
$scope.final_data[j] = data;
}
}
},
templateUrl:'directives/grid.tpl.html',
replace: true
};
});
//The template
<div ng-repeat="data in final_data">
<div layout="vertical" layout-sm="horizontal" layout-padding class="" ng-repeat="row in data">
<div class="" ng-repeat="item in row">
<div flex style="width:100px">
{{item.name}}
</div>
</div>
</div>
//index.html
<div ng-controller="DivisionsCtrl as div">
<material-button ng-click="div.go()" class="material-theme-red">Button</material-button>
<div ng-if="div.data.floors">
<gridy break="3" source="div.data.floors"/>
</div>
the simplest solution would be to use watch
controller: function($scope) {
processData = function () {
var source = $scope.source;
$scope.final_data = new Array(source.length);
if(source){
for(var j=0; j < source.length; ++j){
var total = Math.ceil(source[j]['Division'].length / $scope.break);
var data = new Array(total);
for (var i = 0; i < total; ++i) {
data[i] = source[j]['Division'].slice(i * $scope.break, (i + 1) * $scope.break);
}
$scope.final_data[j] = data;
}
}
}
$scope.$watch('div.data.floors', processData, true)
},

Knockout cross class data binding

Goal: Give the user the ability to adjust mapping results.
I am running into an issue where I need to actually change the instance used of a data bound element. Disclaimer: My json data structure may be off and I am open to possible modifications. I am coding a table header mapping app so a user can verify that the headings mapped by the server are correct. The user will have the ability to map the headers if there is an issue. I have not been able to figure out how to actually update the data bound to the result when the select menu is changed. It feels like it should be super easy. I keep finding myself with basically a finished knockout app less the last step...
Markup Snippet:
<div id="wrapper" data-bind="foreach: headings">
<h1>Bind from this</h1>
<select data-bind="value: selectMenuIdVal, event: { change: updateListing }">
<option> </option>
<!-- ko foreach: $root.headings -->
<option data-bind="value: $data.CC_FIELD_ID, visible: $data.VENDOR_FIELD_NAME(), text: $data.VENDOR_FIELD_NAME"></option>
<!-- /ko -->
</select>
<h1>To this</h1>
<ul data-bind="foreach: listingFields">
<li data-bind="text: $data.VALUE"></li>
</ul>
</div>
KO Snippet:
var Heading = function(data) {
var self = this;
var heading = ko.mapping.fromJS(data, {}, this);
heading.selectMenuIdVal = ko.observable(heading.CC_FIELD_ID());
// heading.listingFields gets mapped by the mapping plugin
this.updateListing = function(ko_evt, js_evt) {
//TODO
// Get the listing results from the value of the select menu
// self.listingFields(those listings);
}
return heading;
}
Here is my fiddle: http://jsfiddle.net/breck421/SLT9B/1/
I really not sure if undertood you right.
Please let me know if this is what you are looking for :
this.updateListing = function (ko_evt, js_evt) {
console.log("fired");
//Do something freaking awesome!!!!!!!
if (vm.dataRepo) {
for (var i = 0; i < vm.dataRepo.HEADINGS.length; i++) {
if (vm.dataRepo.HEADINGS[i].CC_FIELD_ID == heading.selectMenuIdVal()) {
var listingFields = [];
for (var j = 0; j < vm.dataRepo.LISTINGS.length; j++) {
var listing = vm.dataRepo.LISTINGS[j];
var field = listing[i];
if (field) {
listingFields.push(field);
}
}
heading.listingFields(listingFields);
// heading.listingFields = listingFields;
}
}
}
}
See fiddle
I hope it helps.