Filter in controller - Angular - angularjs

I am having trouble with my controller. I am trying to set the default order on page load to display in sequence by number. Right now the the cards just load and one can select an order by.
I need some help please.
Controller:
var cardApp = angular.module('cardApp', []);
cardApp.controller('MainController', ['$scope', function ($scope) {
$scope.greeting = "AngularJS Hello World!";
$scope.subTitle = "AngularJS Intro";
function ctrl($scope, $filter) {
$scope.cards = [
{ "number": "2", "suit": "Hearts", "numOrd": 2 },
{ "number": "10", "suit": "Spades", "numOrd": 10 },
{ "number": "5", "suit": "Spades", "numOrd": 5 },
{ "number": "Q", "suit": "Hearts", "numOrd": 12 }
];
}
}]);
View:
<!doctype html>
<html>
<head>
<title>Starting Angular</title>
</head>
<body ng-app="cardApp">
<div ng-controller="MainController">
<h1 ng-bind="greeting"></h1>
<h3 ng-bind="subTitle"></h3>
<span>Sort By:</span>
<select ng-model="orderProp">
<option value="suit">Suit</option>
<option value="numOrd">Number</option>
</select>
<hr>
<table>
<tr>
<th>Number</th>
<th>Suit</th>
</tr>
<tr ng-repeat="card in cards | orderBy:orderProp">
<td ng-bind ="card.number"></td>
<td ng-bind ="card.suit"></td>
</tr>
</table>
<br />
</div>
<script src="http://code.angularjs.org/1.3.3/angular.min.js"></script>
<script src="js/controllers.js"></script>
</body>
</html>

define a value of orderProp as part of the scope creation just like you did for greeting and subTitle.
$scope.orderProp = 'numOrd';

Related

make JSON array from dynamic form data angular

i have a dynamic form in angular. and i want to send the response as json. how do i generate JSON from the form?
here's the complete code,I have to get json, and post it to some api.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="dyf" ng-submit="submit()">
<form name="userFormOne" novalidate>
<table>
<tr class="form-group" ng-repeat="x in names">
<td><label>{{ x.Field }}</label>
</td><td><input type="text" class="form-control" placeholder="{{x.Comment}}" required>
</td>
</tr>
</table>{{data}}
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('dyf', function($scope, $http) {
$http.get("http://localhost:5000/gu")
.then(function (response) {$scope.names = response.data;console.log(response.data);});
$scope.data ={};
});
</script>
</body>
</html>
In AngularJs we use ng-model to bind inputs value to our controller, sample:
This full sample to figure out how to create a simple form, from array and how to send it as JSON to your API.
Note: On submit check your console, and see the objects value.
var app = angular.module("app", []);
app.controller("ctrl",
function ($scope) {
var options = [
{ name: "a" },
{ name: "b" },
{ name: "c" }
];
$scope.names = [
{ id: 1, field: "insert name", name: "name", placeholder: "your name is", value:null, type:"text" },
{ id: 2, field: "insert phone", name: "phone", placeholder: "your phone is", value: null, type: "tel" },
{ id: 3, field: "insert age", name: "age", placeholder: "your age is", value: null, type: "number", min: 0, max: 20 },
{ id: 4, field: "select country", name: "country", placeholder: "your country is", value: null, type: "select", options: options }
];
$scope.sendMe = function() {
console.log($scope.names);
}
});
<!DOCTYPE html>
<html ng-app="app" ng-controller="ctrl">
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form name="userFormOne" novalidate>
<table>
<tr class="form-group" ng-repeat="x in names">
<td>
<label>{{ x.field }}</label>
</td>
<td ng-if="x.type != 'select'">
<input type="{{x.type}}" min="{{x.min}}" max="{{x.max}}" ng-model="x.value" name="{{x.name}}" placeholder="{{x.placeholder}}" ng-required="true">
{{x.value}}
</td>
<td ng-if="x.type == 'select'">
<select ng-model="x.value" name="{{x.name}}" ng-options="item as item.name for item in x.options">
</select>
{{x.value}}
</td>
</tr>
</table>
<button ng-disabled="userFormOne.$invalid" ng-click="sendMe()">sendMe</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>

how to disable\enable button on checked check box in datatable AngularJS?

I'm show the user list using datatable angularjs. I want to disable\enable button on checked check box.i have the one button this button enable on etlish one checked on check box in the table other wise disable this button.any one how can do that.
this is my button :
<button type="button" class="btn btn-success">Send</button>
This is my controller.js
app.controller("userscontroller", [
"$scope",
"$http",
"DTOptionsBuilder",
"DTColumnBuilder",
"userservice",
"$compile",
function ($scope, $http, DTOptionsBuilder, DTColumnBuilder, userservic, $compile) {
$scope.dtColumns = [
DTColumnBuilder.newColumn("fullName", "Full Name").withOption('name','firstname'),
DTColumnBuilder.newColumn("username", "Name").withOption('name','username'),
DTColumnBuilder.newColumn("email", "Email").withOption('name', 'email'),
DTColumnBuilder.newColumn(null).withTitle('Action').notSortable().renderWith(function (data, type, full, meta) {
return '<button class="btn btn-primary" ng-click="delete(' + data.id + ');"><i class="fa fa-eye"></i>' + '</button>';
}),
DTColumnBuilder.newColumn(null).withTitle('Action').notSortable().renderWith(function (data, type, full, meta) {
return '<input type="checkbox" name="check" id="'+ data.userid +'">';
})
]
$scope.dtOptions = userservice.GetAllUser(DTOptionsBuilder)
.withOption('processing', true)
.withOption('serverSide', true)
.withPaginationType('full_numbers')
.withDisplayLength(50)
.withOption('aaSorting', [3, 'desc']);
function createdRow(row, data, dataIndex) {
$compile(angular.element(row).contents())($scope);
}
}
]);
this is my code so any one idea how can do that please let me know.
Here is a very simple example on how to enable/disable a delete button when checking/unchecking an entry.
angular.module('app', []);
angular.module('app').controller('ExampleController', ['$scope', '$q', function($scope, $q) {
$scope.users = [{
"id": "1",
"fullName": "Marty McFly",
"username": "mmfly",
"email": "mmfly#bttf.com"
},
{
"id": "2",
"fullName": "Robert Plant",
"username": "rplant",
"email": "rplant#ledzep.com"
}
];
$scope.deleteUser = function(id) {
console.log("Deleting user with id", id);
}
}]);
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ExampleController">
<table border="1" cellpadding="8">
<tr>
<th></th>
<th>Fullname</th>
<th>Username</th>
<th>Email</th>
<th>Actions</th>
</tr>
<tr ng-repeat="user in users">
<td><input type="checkbox" ng-model="user._selected"></td>
<td>{{user.fullName}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td><button ng-disabled="!user._selected" ng-click="deleteUser(user.id)">Delete</button></td>
</tr>
</table>
</div>
</body>
</html>

Values should be selected in dropdown once my page is loaded in angularJS (NgRoute)

I am using single page angular application. I have defined the static array in my typescript file. I want to bind my value from my Address array to the dropdown(select control). My ts file is as follows.
let mainAngularModule = angular.module("mm", ['ngMaterial', 'ngRoute']);
mainAngularModule.config(routeConfig);
routeConfig.$inject = ['$routeProvider'];
function routeConfig($routeProvider, $locationProvider) {
$routeProvider
.when('/UserDefinedElement', {
templateUrl: 'LinkType.html',
controller: 'linktController as LTController'
})
.when('/PersonalPreferences', {
templateUrl: 'PersonalPreference.html',
controller: 'personalpreferencesController as PPController'
})
}
and i have defined the class in same ts file which is as follows
class LinkTypeController {
constructor() {
$scope.items = [
{ Name: "LinkType1", Address: "NC"},
{ Name: "LinkType2", Address: "NY"}
];
this.AddressData= [
{ ID: 1, description: "NY" },
{ ID: 2, description: "NC" },
{ ID: 3, description: "SC" },
];
}
}
mainAngularModule.controller("linktController", LinkTypeController);
my Linktype HTML code is as follows
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div class="demo-md-panel-content">
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in items">
<td>{{x.Name}}</td>
<td>
<md-select ng-model="selectedAddress" ng-model-options="{trackBy:'$value.ID'}">
<md-option ng-value="address" ng-repeat="address in LTController.AddressData track by $index">{{ address.description }}</md-option>
</md-select>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
when my page is loaded i want values from my address arrays to be selected in dropdown. Is something i am missing?
<md-select ng-model="x.Address">
<md-option ng-value="address.description" ng-repeat="address in LTController.AddressData track by $index">{{ address.description }}</md-option>
</md-select>
Your ng-model needs to be bound to x.Address which is where the data comes from.
ng-model-options - trackBy needs to be removed because we are doing shallow comparison on string only.
ng-value on option needs to be address.description because this is the field to be matched against x.Address.
I've included a simple example. I'm not familiar with typescript so I've written using vanilla JS.
angular.module('test', ['ngMaterial']).controller('TestController', TestController);
function TestController($scope) {
$scope.items = [
{ Name: "LinkType1", Address: "NC"},
{ Name: "LinkType2", Address: "NY"}
];
$scope.AddressData = [
{ ID: 1, description: "NY" },
{ ID: 2, description: "NC" },
{ ID: 3, description: "SC" },
];
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.3/angular-material.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.3/angular-material.min.js"></script>
<div ng-app='test' ng-controller='TestController'>
<div ng-repeat='x in items'>
<div>Name: {{x.Name}}</div>
<div>
<md-select ng-model='x.Address' aria-label='address'>
<md-option ng-value='address.description' ng-repeat='address in AddressData'>{{address.description}}</md-option>
</md-select>
</div>
</div>
</div>

AngularJS ng-repeat filtering JSON error

I'm learning about AngularJS and I have an error in Chrome console when I do this:
<input ng-model="search" />
<ul>
<li ng-repeat="prof in profesores | filter:search">
{{prof.nombre}} - {{prof.telefono}}
</li>
</ul>
with this data "profesores":
{
"profesores": [
{
"id": 0,
"sexo": "hombre",
"nombre": "Kari",
"snombre": "Carr",
"telefono": "(826) 453-3497",
"celular": "(801) 9175-8136"
},
{
"id": 1,
"sexo": "mujer",
"nombre": "Tameka",
"snombre": "Gamble",
"telefono": "(824) 438-2499",
"celular": "(801) 8595-8337"
} ]
}
The error is this:
The code works correctly (filter the items with string in input) but I have the error in console. What am I doing wrong?
Here ng-repeat="prof in profesores | search" --> wrong
ng-repeat="prof in profesores |filter: search" --> right
var myApp = angular.module('myApp',[]);
myApp.controller('samplecontroller', function($scope) {
$scope.profesores = [
{
"id": 0,
"sexo": "hombre",
"nombre": "Kari",
"snombre": "Carr",
"telefono": "(826) 453-3497",
"celular": "(801) 9175-8136"
},
{
"id": 1,
"sexo": "mujer",
"nombre": "Tameka",
"snombre": "Gamble",
"telefono": "(824) 438-2499",
"celular": "(801) 8595-8337"
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html >
<head>
</head>
<body ng-app="myApp">
<div ng-controller="samplecontroller">
<input ng-model="search" />
<ul>
<li ng-repeat="prof in profesores |filter: search">
{{prof.nombre}} - {{prof.telefono}}
</li>
</ul>
</div>
</body>
</html>
Initialiae it with an empty array like this when js loads:
$scope.profesores = []
Then you can define the variable again in your promise :
$http.get('json/profesores.json') .success(function(data){ $scope.profesores = data.profesores; });
Until the data is loaded from the server your profesores variable is undefined and will throw the error. Initialize it with an empty array at the beginning o your controller:
$scope.profesores = [];
After that you can request the data and fill the array:
$http.get('json/profesores.json').success(function(response){
$scope.profesores = response.profesores;
});

How to delete the row in which a ng-click is located?

In the following code, when I delete a customer, I want the TR row to disappear.
What is the best way to do this? Do I need to send the row as a parameter to deleteCustomer somehow? Do I have access to the TR DOM element within AngularJS somehow?
<html ng-app="mainModule">
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="mainController" style="padding: 20px">
<div class="col-lg-5">
<table style="width: 500px" class="table-striped table-bordered table table-hover">
<tr ng-repeat="customer in customers">
<td style="width:50px"><button ng-click="deleteCustomer(customer)">Delete</button></td>
<td style="text-align:right">{{customer.id}}</td>
<td>{{customer.firstName}}</td>
<td>{{customer.lastName}}</td>
</tr>
</table>
</div>
<div class="col-lg-7">
<div class="panel panel-info">
<div class="panel-heading">Logger</div>
<div class="panel-body" style="padding:0">
<table class="table table-bordered" style="margin:0">
<tr ng-repeat="loggedAction in loggedActions">
<td>{{loggedAction.action}}</td>
<td>{{loggedAction.description}}</td>
</tr>
</table>
</div>
</div>
</div>
<script>
var mainModule = angular.module('mainModule', []);
function mainController($scope) {
$scope.loggedActions = [];
$scope.customers = [
{id: 1, firstName: 'Joe', lastName: 'Thompson'},
{id: 2, firstName: 'Hank', lastName: 'Howards'},
{id: 3, firstName: 'Zoe', lastName: 'Frappe'}
];
$scope.deleteCustomer = function (customer) {
$scope.$emit('customerDeleted', customer);
};
$scope.$on('customerDeleted', function (event, customer) {
$scope.loggedActions.push({action: 'delete', description: 'Deleted customer ' + customer.firstName + ' ' + customer.lastName});
});
}
</script>
</body>
</html>
EDIT:
as pointed out by #K.Toress's comment, it's better to retrieve the index of the deleted customer via indexOf() from within the function, rather than passing $index from the ng-repeat.
passing $index will give unexpected results if using a filter or sorting the array.
deleteCustomer function:
$scope.deleteCustomer = function (customer) {
var index = $scope.customers.indexOf(customer);
$scope.customers.splice(index, 1);
$scope.$emit('customerDeleted', customer);
};
updated plnkr
you can use the $index provided by ng-repeat, and array.splice from within the delete function:
html:
<button ng-click="deleteCustomer($index, customer)">Delete</button>
js:
$scope.deleteCustomer = function ($index, customer) {
$scope.customers.splice($index, 1);
$scope.$emit('customerDeleted', customer);
};
plnkr
Working example:
http://plnkr.co/edit/7MOdokoohX0mv9uSWuAF?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.data = ['a', 'b', 'c', 'd', 'e'];
$scope.delete = function(at) {
$scope.data.splice(at, 1);
}
});
Template:
<body ng-app="plunker" ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div ng-repeat="elem in data">
{{elem}}
<button ng-click="delete($index)">delete {{elem}}</button>
</div>
</body>

Resources