Dropdown Option is not selected - angularjs - angularjs

I am binding numbers to a dropdown.
When page loads, the default number selected is 3. It should be 1.
Also, when I select other options like 2 & 1 in the dropdown, there are not selected. It just remains 3. Why is this happening.
Issue:
The problem is with the ng-class. If I remove the ng-class expression for Next, it works fine. But I want the Next & Last to be disabled, when user selects the last page.
I guess, $scope.LastPageNumber is assigned in a promise and hence the value doesnt stay. That's the reason for the bug.Isn't it. But then how to fix this.
HTML:
<ul class="pagination custom-pagination">
<li ng-class="{disabled: SelectedPage<=1}">First</li>
<li ng-class="{disabled: SelectedPage<=1}">Prev</li>
<li>
<select ng-model="SelectedPage" ng-options="Number for Number in PageNumbers">
</select>
</li>
<li ng-class="{disabled: SelectedPage=LastPageNumber}">Next</li>
<li>Last</li>
</ul>
JS:
$scope.SelectedPage;
$scope.LastPageNumber;
$scope.PageNumbers = [];
$scope.UserReport = [];
GetReport();
console.log($scope.SelectedPage); //print undefined
console.log($scope.LastPageNumber); //print undefined
function GetReport() {
var promise = Factory.GetReport();
promise.then(function (success) {
if (success.data != null && success.data != '') {
$scope.UserReport = JSON.parse(success.data);
BindPageNumbers(9);
}
else {
$scope.UserResponsesReport = [];
}
},
function (error) {
console.log(error);
});
}
function BindPageNumbers(totalRows) {
$scope.LastPageNumber = Math.ceil((totalRows / 3));
for (var i = 1; i <= $scope.LastPageNumber ; i++) {
$scope.PageNumbers.push(i);
}
$scope.SelectedPage = $scope.PageNumbers[0]; //set default page number as 1
console.log($scope.PageNumbers[0]); //prints 1
}

You can do it like this:
var app = angular.module('App',[]);
app.controller("ctrl",function($scope){
$scope.SelectedPage;
$scope.LastPageNumber;
$scope.PageNumbers = [];
BindPageNumbers(9);
function BindPageNumbers(totalRows) {
$scope.LastPageNumber = Math.ceil((totalRows / 3));
for (var i = 1; i <= $scope.LastPageNumber ; i++) {
$scope.PageNumbers.push(i);
}
$scope.SelectedPage = $scope.PageNumbers[0]; //set default page number as 1
}
});
And in HTML:
<body ng-app="App" ng-controller="ctrl">
<select ng-model="SelectedPage" ng-options="number for number in PageNumbers"></select>
Here is the plunker

You should use the ng-options directive:
HTML:
<div ng-app="app">
<div ng-controller="mainController">
<select ng-model="SelectedPage" ng-options="PageNumber for PageNumber in PageNumbers">
</select>
{{SelectedPage}}
</div>
</div>
JS:
angular.module('app', [])
.controller('mainController', function($scope) {
$scope.PageNumbers = [1, 2, 3];
$scope.SelectedPage = $scope.PageNumbers[0];
});
Working fiddle here: http://jsfiddle.net/ben1729/daL8r5b9/1/

<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selected" ng-options="number for number in PageNumbers">
<option>{{number}}</option>
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.PageNumbers = [1,2,3];
$scope.selected=$scope.PageNumbers[0];
});
</script>
</body>

Related

Angularjs ng-change and ng-repeat not properly working

In ng-change the selected value is not setting up in the ngchange function.
First time when I select a value its setting up as null, and again I try to select an another value, its setting the value of the previous selected value.
var ngInitParams = JsonConvert.SerializeObject(Model);
var firstVarId= Model.Variants.First().ProductId;
var firstVarName= Model.Variants.First().Name;
<section id="#inPageNavigationID" ng-controller="prodSpecsCtrl as main"
ng-init="main.init('#firstVarId', '#firstVarName')">
<div class="container" ng-init="main.loadSelect('#ngInitParams')">
<div>
<div class="row">
<div class="col-sm-6 fieldset">
<div class="form__item ">
<div>
<select class="-dropdown--two-columns" name="productvariants" id="sel1" data-placeholder="#selectOptionVal" ng-model="variant.ProductId"
ng-change="main.load('{{variant.ProductId}}','{{(main.JsonVariants.Variants | filter: {ProductId:variant.ProductId})[0].Name}}')">
<option value="" disabled>Select Model</option>
<option ng-repeat="variant in main.JsonVariants.Variants" value="{{variant.ProductId}}" selected="#firstVariantId" data-option-header="{{variant.CatalogCode}}">{{variant.Name}}</option>
</select>
<span class="fa fa-angle-down"></span>
</div>
</div>
</div>
</div>
</div>
<section>
this.init = function (varId, varName) {
this.load(varId, varName);
}
this.loadSelect = function (strjson) {
self.JsonVariants = JSON.parse(strjson);
}
Here is an example of an ng-change within a select.
https://plnkr.co/edit/ZhJbVfPRCLoeFwYoi3Mp?p=preview
<body ng-controller="MainCtrl">
<select ng-model="item" ng-change="changed(item)" ng-options="item.Name for item in items"></select>
<p>ID:{{selected.ID}} Name: {{selected.Name}}</p>
<p>You Selected: {{selected}}</p>
</body>
And Controller:
app.controller('MainCtrl', function($scope) {
$scope.items = [];
$scope.selected = {};
$scope.changed = function(item) {
$scope.selected = item;
}
function setupItems() {
for (var i = 0; i < 10; i++) {
var item = {ID: i, Name: "Item " + i}
$scope.items.push(item);
}
}
setupItems();
});

ng-style assign dynamic scope variable from $index

I'm trying to assign a scope variable's value to an ng-style directive but the name is not parsing.
What am I doing wrong? When you press the TEST button it should turn the text to RED but the scope variable is not parsing as it's name is dynamic. I've tried multiple different syntax which all didn't work.
Here is the html:
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="Test()">test</button>
<div ng-repeat="item in items">
<div ng-style="{{'DynamicVariable-'+$index}}">
{{someone.name}}
</div>
</div>
</div>
controller code
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.someone = {
name: 'John'
};
$scope.items=[1,2,3,4,5,6,7,8,9];
$scope.mainId = 1;
$scope.Test=function(){
for(var i=0;i<$scope.items.length;i++){
$scope["DynamicVariable-"+i]={color:'red'};
}
console.log($scope);
};
}]);
js fiddle that doesn't work:
http://jsfiddle.net/avboivin/0qov365b/4/
It has a problem with '-', try to remove it
html:
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="Test()">test</button>
<div ng-repeat="item in items">
<div ng-style="{{'DynamicVariable'+$index}}">
{{ someone.name }}
</div>
</div>
</div>
controller:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function ($scope) {
$scope.someone = {
name: 'John'
};
$scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$scope.mainId = 1;
$scope.Test = function () {
for (var i = 0; i < $scope.items.length; i++) {
$scope["DynamicVariable" + i] = { color: 'red' };
}
console.log($scope);
};
}]);
fork

How to print (on ng-click) an item of a ng-repeat outside the loop?

I have a simple array of objects {name,age} (see my jsfiddle). I use an ng-repeat to print all the names and I would like to print, outside the ng-repeat loop, the age of the name on which I click.
<body ng-app="myapp">
<div ng-controller="MyController" >
<ul>
<li ng-repeat="friend in myData.friends" ng-click="myData.doClick($index)">{{friend.name}}</li>
</ul>
<p>Age :</p>
<p>{{}}</p>
</div>
<script>
angular.module("myapp", []).controller("MyController", function($scope) {
$scope.myData = {};
$scope.myData.friends = [{ name: "Al",age:26}, { name: "Mike",age:21}, { name: "Brian",age:46} ];
$scope.myData.doClick = function(item) {
}
} );
</script>
</body>
Instead of passing the $index, you should pass the object itself, friend, then you can read his information.
Quick refactoring: http://jsfiddle.net/par2nrd4/4/
The below code should work for you....
<body ng-app="myapp">
<div ng-controller="MyController" >
<ul>
<li ng-repeat="friend in myData.friends" ng-click="myData.doClick(friend.name)">{{friend.name}}</li>
</ul>
<p>Age :</p>
<p>{{ageval}}</p>
</div>
<script>
angular.module("myapp", []).controller("MyController", function($scope) {
$scope.myData = {};
$scope.myData.friends = [{ name: "Al",age:26}, { name: "Mike",age:21}, { name: "Brian",age:46} ];
$scope.myData.doClick = function(item) {
for (i = 0; i < $scope.myData.friends.length; i++) {
if (item == $scope.myData.friends[i]["name"]) {
$scope.ageval = $scope.myData.friends[i]["age"];
}
}
}
} );
</script>
</body>

AngularJS show 2 random records

I just started up learning AngularJS and I have no idea how to solve this problem. For example I have 4 records (car, plane, ship, train) and I only want to show 2 randomly in ng-repeat.
Examples:
1.st. plane, ship
2.nd. car, train
3.rd. train, plane
So how would syntax look like ?
JS:
app.controller('WorkCtrl', function($scope, $http) {
$http.get('work.json').success(function(work) {
$scope.work = work;
});
});
HTML:
<div class="work" ng-controller="WorkCtrl">
<ul class="grid">
<li ng-repeat="work in work">
<a href="#{{ work.link }}" target="blank_">
<div class="background"></div>
<h3 class="name">#{{ work.name }}</h3>
<p class="description">#{{ work.description }}</p>
<img ng-src="#{{ work.image_path }}">
</a>
</li>
</ul>
</div>
I created something like this:
var app = angular.module("myApp", []);
app.controller('myCtrl', ['$scope', function($scope){
$scope.records = ['plane', 'train', 'car', 'submarine'];
}]);
app.filter('randomSelection', function(){
return function(inputArray, numItemsToReturn){
// assuming you pass an array, not doing checking here
if(!inputArray)
return inputArray;
var numItems = inputArray.length;
var min = 0;
var max = numItems-1;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
while (inputArray.length > numItemsToReturn){
inputArray.splice(random, 1);
}
return inputArray;
};
});
HTML:
<div ng-repeat="record in records | randomSelection : 2">
{{record}}
</div>
Seems to work, no infdigest loop. You may want to add another condition in the while loop to break out so as to avoid an infinite loop.
http://embed.plnkr.co/mJ5Q7n24uLnELSNPUB9z/script.js
<div ng-repeat="w in work = (work|orderBy:randomize).slice(0, 2)">
$scope.randomize = function () {
return 0.5 - Math.random();
};
Demo: http://jsfiddle.net/hmx2zqex/

trying to use ngSwitch in angular

I'm testing the following code in angular and it's not working. I'm very new to Angular and I've been unable to figure this out. All I'm trying to do is show a particular element based on a step number when next/back buttons are clicked.
<div ng-app ng-controller="Ctrl">
<div ng-switch on="selection" >
<div ng-switch-when="2" step-number="2">Settings Div</div>
<span ng-switch-when="1" step-number="1">Home Span</span>
<span ng-switch-default step-number="3">default</span>
<button ng-click="back(step-number)">back</button>
<button ng-click="forward(step-number)">forward</button>
</div>
</div>
function Ctrl($scope) {
$scope.items = ['1', '2', '3'];
$scope.forward = function($selected) { $scope.selection = $scope.items[$selected - 1]; };
$scope.back = function($selected) { $scope.selection = $scope.items[$selected - 1]; };
}
I think I would refactor what you are doing to the following:
Demo: http://plnkr.co/edit/b7mQ5ssSqECDUhvN0S2b?p=preview (click back first).
app.controller('Ctrl', function($scope) {
$scope.name = 'World';
$scope.selection = 2;
$scope.items = ['div 1', 'div 2', 'div 3'];
$scope.forward = function() {
if ($scope.selection==$scope.items.length-1) $scope.selection=0;
else $scope.selection++;
};
$scope.back = function() {
if ($scope.selection==0) $scope.selection = $scope.items.length-1;
else $scope.selection --;
};
});
<body ng-controller="Ctrl">
<div >
<div>
<div>{{items[selection]}}</div>
<button ng-click="back()">back</button>
<button ng-click="forward()">forward</button>
</div>
</div>
</body>
I'm not sure what you are trying to do with step-number, but here is a way to make your buttons work between the values of 1 and 3 inclusive:
<div ng-switch on="selection">
<div ng-switch-when="2">Settings Div</div>
<span ng-switch-when="1">Home Span</span>
<span ng-switch-default step-number="3">default</span>
<button ng-click="back()">back</button>
<button ng-click="forward()">forward</button>
</div>
function MyCtrl($scope) {
$scope.selection = 3;
$scope.forward = function () {
$scope.selection += 1;
if ($scope.selection > 3) $scope.selection = 3;
console.log($scope.selection);
};
$scope.back = function () {
$scope.selection -= 1;
if ($scope.selection < 1) $scope.selection = 1;
console.log($scope.selection);
};
}
fiddle

Resources