Replace option values - angularjs

I'm trying to update the options after 3 seconds.
In my HTML I have the code that generates the options.
<select
ng-model="selectedOperator"
ng-options="operator as operator.name for operator in operators">
</select>
And in the same HTML, I have
$(function() {
$('select').material_select();
});
that initializes the Materialize dropdown.
In my Javascript:
.controller('MainCtrl', function ($scope, $timeout) {
// initialize old(first) values
$scope.operators = [
{ value: 1, name: 'Old-One' },
{ value: 2, name: 'Old-Two' }
];
$scope.selectedOperator = null; // no default selected value
// after three seconds, replace the old value with new one.
$timeout(function() {
$scope.operators = [{ value: 10, name: 'New Awesome' }];
// reinitialize the materialize select.
$('select').material_select();
}, 3000);
});
However it's not being updated, it's still generating the old value.
In the HTML, the value of {{ operators }} is the new value.
I'm new to Angular, any help would be greatly appreciated.
Cheers
Update: I'm like 70% sure they don't play well with each other, made a temporary fix by replacing select with radio button.

<select name="repeatSelect" id="repeatSelect" ng-model="selectedOperator">
<option ng-repeat="operator in operators" value="{{operator.value}}">{{operator.name}}</option>
</select>
DOC

This is sample example you can change this values later, its working fine.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function() {
$('select').material_select();
});
angular.module('myApp', []).controller('namesCtrl', function($scope, $timeout) {
$scope.operators = [
{ value: 1, name: 'Old-One' },
{ value: 2, name: 'Old-Two' }
];
$scope.selectedOperator = null; // no default selected value
// after three seconds, replace the old value with new one.
$timeout(function() {
$scope.operators = [{ value: 10, name: 'New Awesome' }];
// reinitialize the materialize select.
$('select').material_select();
}, 3000);
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<h1>Angular JS Application</h1>
<select ng-model="selectedOperator" ng-options="operator as operator.name for operator in operators">
</select>
</div>
</body>

Related

Angular different option value or string given an expression in select dropdown

I am creating a <select/> with a default <option/> string but it relies on a specific expression
For example, an empty data set would yield a "No Data yet" default option while when there is data available the default option should be "Select a Data"
Angular only allows one static option in the html page.
Make the option description conditional (by moving the description to a function):
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function($scope) {
$scope.people = [{
first: 'John', last: 'Rambo'
}, {
first: 'Rocky', last: 'Balboa'
}, {
first: 'John', last: 'Kimble'
}, {
first: 'Ben', last: 'Richards'
}];
$scope.optionText = function() {
if($scope.people.length > 0) return 'Select a person';
else return 'No person found';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="FirstCtrl">
<select ng-options="p.first + ' ' + p.last for p in people" ng-model="selectedPerson">
<option value="">{{optionText()}}</option>
</select>
<button ng-click="people = []">Clean data</button>
</div>

Computed values in angular-schema-form

I have a form which is used to enter a bunch of values. I want to show various calculation on the values, but dynamically, so that when a number is changed the results immediately update. I thought that this should work, but it doesn't - i.e. the calculation is never run:
angular.module('calcs', ['schemaForm'])
.controller('CalcCtrl', function ($scope) {
$scope.schema = {
type: 'object',
properties: {
width: {
type: 'number',
title: 'Width'
},
depth: {
type: 'number',
title: 'Depth'
}
}
};
$scope.form = ['*'];
$scope.model = {};
$scope.$watch('[model.width, model.depth]', function() {
// This function is never called
$scope.area = $scope.model.width * $scope.model.depth;
});
});
I have seen this question, but I am doing quite a number of calculations and I really don't want to have to create a directive for each, so I am hoping there is another way. For reference, here is my template:
<div ng-controller="CalcCtrl">
<form sf-schema="schema" sf-form="form" sf-model="model"></form>
<p>Area: {{area}}</p>
</div>
I believe what you want is $watchCollection:
$scope.$watchCollection('[model.width, model.depth]', function() {
// This function is never called
$scope.area = $scope.model.width * $scope.model.depth;
});
example:
var app = angular.module('app', []);
app.controller('myController', function($scope) {
$scope.model = {}
$scope.$watchCollection('[model.width,model.height]', function() {
$scope.area = $scope.model.width * $scope.model.height;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController">
<input ng-model="model.width">
<input ng-model="model.height">
{{area || ''}}
</div>
<div>

How to chain AngularJS filters in controller

I have few filters in view
<tr ng-repeat="x in list | filter:search| offset:currentPage*pageSize| limitTo:pageSize ">
In my project to achieve good result, i have to make this filtering in controller not in view
i know the basic syntax $filter('filter')('x','x') but i don't know how to make chain of filters in controller, so everything will work as in my example from template.
I found some solution, now just with one filter, but should work with many ;)
$scope.data = data; //my geojson from factory//
$scope.geojson = {}; //i have to make empty object to extend it scope later with data, it is solution i found for leaflet //
$scope.geojson.data = [];
$scope.FilteredGeojson = function() {
var result = $scope.data;
if ($scope.data) {
result = $filter('limitTo')(result,10);
$scope.geojson.data = result;
console.log('success');
}
return result;
};
and i use this function in ng-repeat works fine, but i have to check it with few filters.
You can just re-filter what you get returned from your first filter. So on and so forth.
var filtered;
filtered = $filter('filter')($scope.list, {name: $scope.filterParams.nameSearch});
filtered = $filter('orderBy')(filtered, $scope.filterParams.order);
Below plunkr demonstrates the above.
http://plnkr.co/edit/Ej1O36aOrHoNdTMxH2vH?p=preview
In addition to explicitly applying filters to the result of the previous one you could also build an object that will chain multiple filters together.
Controller
angular.module('Demo', []);
angular.module('Demo')
.controller('DemoCtrl', function($scope, $filter) {
$scope.order = 'calories';
$scope.filteredFruits = $scope.fruits = [{ name: 'Apple', calories: 80 }, { name: 'Grapes', calories: 100 }, { name: 'Lemon', calories: 25 }, { name: 'Lime', calories: 20 }, { name: 'Peach', calories: 85 }, { name: 'Orange', calories: 75 }, { name: 'Strawberry', calories: 65 }];
$scope.filterFruits = function(){
var chain = new filterChain($scope.fruits);
$scope.filteredFruits = chain
.applyFilter('filter', [{ name: $scope.filter }])
.applyFilter('orderBy', [ $scope.order ])
.value;
};
function filterChain(value) {
this.value = value;
}
filterChain.prototype.applyFilter = function(filterName, args) {
args.unshift(this.value);
this.value = $filter(filterName).apply(undefined, args)
return this;
};
});
View
<!doctype html>
<html ng-app="Demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script src="script.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="DemoCtrl">
<input type="text" ng-model="filter" ng-change="filterFruits()" placeholder="Filter Fruits" />
<select ng-model="order">
<option value="name">name</option>
<option value="calories">calories</option>
</select>
<div ng-repeat="fruit in filteredFruits">
<strong>Name:</strong> {{fruit.name}}
<strong>Calories:</strong> {{fruit.calories}}
</div>
</div>
</body>
</html>
This is a typical case for FP libraries like lodash or Ramda. Make sure your common data is applied as last arg to each filter. (in this case columns)
$scope.columnDefs = _.compose(
$filter('filter3'),
$filter('filter2'),
$filter('filter1')
)($scope.columns)
or with extra args
$scope.columnDefs = _.compose(
$filter('filter3').bind(null, optionalArg1, optionalArg2),
$filter('filter2').bind(null, optionalArg1),
$filter('filter1')
)($scope.columns)

I can not get the select working correctly in angularjs

I tried to do as this article recommends to get select-options working in AngularJS.
http://gurustop.net/blog/2014/01/28/common-problems-and-solutions-when-using-select-elements-with-angular-js-ng-options-initial-selection/
However I have got it messed up some how. Here is a fiddlerjs of the code
http://jsfiddle.net/8faa5/
Here is the HTML
<!DOCTYPE html>
<html class="no-js" data-ng-app="TestModule">
<head>
<title></title>
</head>
<body data-ng-controller="TestController">
<h3>Test Select</h3>
Current Value: {{ ourData.CurrentSelected}} <br>
<select ng-init="ourData._currVal = {Value: ourData.CurrentSelected}"
ng-change="ourData.CurrentSelected = ourData._currVal.Value"
ng-model="ourData._currVal"
ng-options="oneItem.Value as oneItem.Disp
for oneItem in ourData.StuffForDropDown track by oneItem.Value"></select>
<!-- Get Javascript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="js/data.js"></script>
</body>
</html>
Here is js/data.js
(function() {
"use strict";
var smallData = {
StuffForDropDown: [
{
Disp: "01-Prospect",
Value: 5
},
{
Disp: "02-Constituet Issue",
Value: 10
}
],
CurrentSelected: "10"
};
var myModule = angular.module("TestModule", ['ui.mask']);
myModule.controller("TestController", ["$scope",
function ($scope){
$scope.ourData = smallData;
}
]);
})();
First of all, your jsfiddle is messed up. You have defined angularjs twice, once in the jsfiddle options and the second time in the code. Also you overcomplicated your code. I made a simple rewrite of your code that is working in this jsfiddle.
<div data-ng-app="TestModule">
<div data-ng-controller="TestController">
<h3>Test Select</h3>
Current Value: {{ ourData._currval}}
<br>
<select ng-init="ourData._currVal = {Value: ourData.CurrentSelected}"
ng-model="ourData._currval" ng-options="oneItem.Value as oneItem.Disp
for oneItem in ourData.StuffForDropDown"></select>
</div>
</div>
(function () {
"use strict";
var smallData = {
StuffForDropDown: [{
Disp: "01-Prospect",
Value: 5
}, {
Disp: "02-Constituet Issue",
Value: 10
}],
CurrentSelected: "10"
};
var myModule = angular.module("TestModule", []);
myModule.controller("TestController", ["$scope",
function ($scope) {
$scope.ourData = smallData;
}]);
})();
**Edit:
OK, I have revised my code according to your new request int the comment. The code goes as follows (new plunker)
<div data-ng-app="TestModule">
<div data-ng-controller="TestController">
<h3>Test Select</h3>
Current Value: {{ currentItem.Value}}
<br>
<select ng-model="currentItem" ng-options="u as u.Disp for u in items track by u.Value"></select>
</div>
</div>
(function () {
"use strict";
var myModule = angular.module("TestModule", []);
var ctrl = function ($scope) {
$scope.items = [{
Disp: "01-Prospect",
Value: 5
}, {
Disp: "02-Constituet Issue",
Value: 10
}];
$scope.currentItem = $scope.items[1];
};
myModule.controller("TestController", ctrl)
})();

using ng-model in ng-repeat angularjs

I am having some problems with angular. Now I have a following code :
<div ng-repeat='item in items'>
<span>{{item.title}}</span>
<input ng-change="test()" ng-model='abc'> {{abc}}
<span>{{item.price| currency}}</span>
<span>{{item.price * item.quantity| currency}}</span>
<button ng-click="remove($index)">Remove</button>
</div>
<script type="text/javascript" src="libs/angular.min.js"></script>
<script>
function CartController($scope) {
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
$scope.test = function() {
console.log($scope.abc);
}
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
</script>
I wanna know why I can not console.log abc value in controller? My English is bad, pls help me. Thanks in advance
Try changing
$scope.test = function() {
console.log($scope.abc);
}
to
$scope.test = function() {
console.log(this.abc);
}
"this" will resolve to the current scope object and you should be able to print the value as you keep changing the text.
What happens if you declare abc as a variable before trying to use it?
function CartController($scope){
var $scope.abc = 'foo';
...

Resources