Angularjs ng-select selected value not set - angularjs

I am trying to populate a form to edit a user list.
index.html:
<h1>Users</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="u in users" data-ng-click="select(u)">
<td>{{u.id}}</td>
<td>{{u.username}}</td>
<td>{{u.role.title}}</td>
</tr>
</tbody>
</table>
<form>
<label for="inputUsername">Username</label>
<input data-ng-model="selectedUser.username" id="inputUsername" type="text">
<select data-ng-model="selectedUser.role"
data-ng-options="r as r.title for r in roles"
data-ng-change="">
</select>
</form>
<pre>{{selectedUser |json}}</pre>
controllers.js:
angular.module('test-select')
.controller('IndexCtrl',
['$scope', 'Restangular', function($scope, Restangular) {
$scope.selectedUser = null;
Restangular.all("roles").getList().then(function(roles) {
$scope.roles = roles;
});
Restangular.all("users").getList().then(function(users) {
$scope.users = users;
});
$scope.select = function(user) {
$scope.selectedUser = user;
};
}]);
What I want to achieve is, when I click on a row on the table I can edit the selected user in the form (to save the new values) Everything works fine, except for the users role. If I click on a row, the selected user role is not updated.
I think that has to do with the fact thaT the role list via Restangular call. Has anyone an Idea how I can solve this problem elegantly?
PS: I am using angular 1.2-rc2.
BR, Rene

The following solution works but I think it is not very elegant:
index.html:
<h1>Users</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="u in users" data-ng-click="select(u)">
<td>{{u.id}}</td>
<td>{{u.username}}</td>
<td>{{u.role.title}}</td>
</tr>
</tbody>
</table>
<form>
<label for="inputUsername">Username</label>
<input data-ng-model="selectedUser.username" id="inputUsername" type="text">
<select data-ng-model="selectedUser.role.id"
data-ng-options="r.id as r.title for r in roles"
data-ng-change="update()">
</select>
</form>
controller.js:
'use strict';
/* Controllers */
angular.module('test-select')
.controller('IndexCtrl',
['$scope', 'Restangular', '$resource', function($scope, Restangular, $resource) {
$scope.selectedUser = null;
Restangular.all("roles").getList().then(function(roles) {
$scope.roles = roles;
});
Restangular.all("users").getList().then(function(users) {
$scope.users = users;
});
$scope.select = function(user) {
$scope.selectedUser = user;
};
$scope.update = function() {
var role = _.find($scope.roles, function(role){
return role.id === $scope.selectedUser.role.id;
});
$scope.selectedUser.role.title = role.title;
$scope.selectedUser.role.bitMask = role.bitMask;
}
}]);

Related

Selecting default value using ngModel ngRepeat, ngOptions

Hopefully someone can help.
I am developing an application using HTML AngularJs which uses ng-repeat,ng-options and ng-model and populates multiple rows based on the data in the database for a user. Each row has static data coming from DB (returned as object via restAPI) and dynamic select option for user selection. Select option is hardcoded in app.js and linked to model on HTML for DB update upon selection using update button. Each row has its own button and i can see update function is working at row level.
I want to set the default value of the drop down list dynamically as value of an element coming from database. Object is same as one being used to populate rows with static data .
Code is in the fiddle at https://jsfiddle.net/6j88L61y/4/
HTML below
<body>
<h1 align="center">User Tracker</h1>
<div ng-controller="MainController as main">
<div>
<p>Please Enter ID </p>
<p>
<input type="text" ng-model="main.model.userName"></input>
<button ng-click="main.model.getOrgList()">List State List</button>
</p>
</div>
<hr ng-show="main.model.formSubmitted"></hr>
<div>
<table class="table table-bordered" border="1">
<thead>
<tr>
<th>ID</th>
<th>User Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="org in main.model.orgList" id="{{org.id}}">
<td>{{org.id}}</td>
<td align="center">{{org.user}}</td>
<td align="center">
<select ng-model="main.model.selectedRecord.appCurrentStateSelected[$index]" ng-options="option.value as option.value for option in main.model.appCurrentStateList" ></select>
</td>
<td>
<button ng-click="main.model.updateAppDetailsList({id:org.id,userName:org.name,appCrntState:main.model.selectedRecord.appCurrentStateSelected})">Update</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
JS
"use strict";
angular.module('myApp',[]);
angular.module('myApp').service('AppModel', function( $http) {
this.userId='';
this.userName ="";
this.formSubmitted="";
this. selectedRecord ={appCurrentStateSelected:''};
this.appCurrentStateList =[{name: 'New',value:'New',id:1}, {name: 'InUse',value:'InUse',id:2},{name: 'Inactive',value:'Inactive',id:3},{name: 'Deleted',value:'Deleted',id:4}];
this.submittedAppDetailsList=[];
console.log(' json sample:'+this.submittedAppDetailsList);
var path = 'home';
var currentProtocol = location.protocol;
var host =location.host;
var apiHost = currentProtocol+'//'+host+'/api/';
console.log('API url is : ' +apiHost);
// Get method
this.getOrgList = function() {
var path = 'home/userid';
console.log(this.userName);
console.log(this.selectedRecord);
$http.get(apiHost+path+'/'+this.userName+'/')
.then(function(response) {
this.orgList =response.data;
this.formSubmitted = true;
console.log(response.data);
}.bind(this),
function(response) {
console.log(response.data);
});
}
// Post method
this.updateAppDetailsList = function(appdetailsList) {
var path = 'home/update';
console.log(this.selectedRecord);
$http.post(apiHost+'home/update/',appdetailsList)
.then(function(response) {
this.submittedAppDetailsList.push(response.data);
this.formSubmitted = false;
console.log(response.data);
}.bind(this),
function(response) {
console.log('Error : '+response.data);
});
}
});
angular.module('myApp').controller('MainController', ['AppModel', function (AppModel) {
this.model = AppModel;
}]);

What is the proper way to use filters?

I get an issue using $filter('filter') of AngularJS. It seems not working when I have an empty cell in the line...
When a cell is empty on a line if I add a filter it works but when removing the filter the line with the empty cell is deleted from contacts...
AngularJS script :
app.controller("ContactNgController", function($scope, $http, $filter, $document) {
$http.get('/api/mes-contacts').success(function(data, status, headers, config) {
$scope.contacts = data.contacts;
$scope.filteredContacts = data.contacts;
$scope.nbContacts = data.contacts.length;
$scope.limit = data.limit;
$scope.onChange = function(){
$scope.contacts = data.contacts;
$scope.filteredContacts = $filter('filter')($scope.contacts, $scope.search);
};
});
});
Table HTML :
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Prénom<input type="text" ng-model="search.firstname" placeholder="Recherche par prénom" ng-change="onChange()" autocomplete="off"></th>
<th>Nom<input type="text" ng-model="search.lastname" placeholder="Recherche par nom" ng-change="onChange()" autocomplete="off"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts | filter:search | limitTo:limit">
<td>{{contact.firstname}}</td>
<td>{{contact.lastname}}</td>
</tr>
</tbody>
</table>
(source: zupimages.net)

bootstrap-table not rendering upon updating model in Angular

Hi I am not able to render table using bootstrap-table and angular. here is my code, I think I need to call bootstrap-table init method in angular ajax call. Can some one guide me on how to do this..?
angular
.module('reports')
.controller(
'ReportCtrl',
[
'$scope',
'$http',
'ngProgress',
function($scope, $http, ngProgress) {
var vm = this;
vm.mdp = {};
vm.mdp.data = [];
vm.mdp.columns = [];
$scope.submit = function() {
var report = $scope.tab;
$http.post('/reports/cmd/getData', {
report : report,
date : createdAfter
}).success(function(data) {
vm.mdp.data = data;
$.each(data[0], function(key, value){
vm.mdp.columns.push(key);
});
}).error(function(error) {
alert(error);
});
};
} ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mdp" class="panel" ng-controller="ReportCtrl as report" ng-show="panel.isSelected('mdp')">
<table data-toggle="table" data-show-columns="true" data-search="true" data-show-export="true" data-pagination="true" data-height="299">
<thead>
<tr>
<th ng-repeat="c in report.mdp.columns" data-field= {{c}} >{{ c }}</th>
</tr>
</thead>
<tr ng-repeat="r in report.mdp.data">
<td ng-repeat="c in report.mdp.columns">{{ r[c] }}</td>
</tr>
</table>
</div>
Integrating Bootstrap Table with Angular is solved here:
https://github.com/wenzhixin/bootstrap-table/issues/165
https://github.com/AkramKamal/bootstrap-table-examples/tree/master/integrate
I have some minor changes in my implementation of this solution which I will upload to Github / JSFiddle shortly. But the links above will allow you to get going.

Breaking the ice on angular

I have a view:
<div id="productList" ng-controller="ProductController">
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th width="100%">Item ID</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in productItems">
<td><input type="checkbox" /></td>
<td><% item.ID %></td>
</tr>
</tbody>
</table>
</div>
I have a controller:
var TestApp = angular.module('TestApp', [], function( $interpolateProvider ) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
TestApp.controller('ProductController', function ( $scope ) {
ProductRepository.GetPaginatedProducts();
$scope.productItems = ProductRepository.Model;
});
I have a model:
var ProductRepository = function ()
{
return {
Model: null,
GetPaginatedProducts: function()
{
$.ajax( {
"url": Test.URL + "/json/products/paginated",
"dataType": "json",
"method": "post",
"success": function( data )
{
ProductRepository.Model = data;
}
} );
},
}
}
When the ajax finished, it updates the ProductRepository.Model data variable which I want the angular controller scope.productItems to work off of.
This is my first time using angular and i think I've missed the point,
Why is the table not updating with the information?
Please see here for sample ajax call http://plnkr.co/edit/5CiC8MWiwo010nwu32he?p=preview
var TestApp = angular.module('plunker', []);
TestApp.factory('ProductRepository', function($http, $q) {
var Model = [];
return {
Model: Model,
GetPaginatedProducts: function() {
var deferred = $q.defer();
$http.get('paginated.json').then(
//sucess
function(result) {
deferred.resolve(result.data)
}
//error
, function() {});
return deferred.promise;
}
};
})
TestApp.controller('ProductController', function($scope, ProductRepository) {
$scope.productItems = [];
ProductRepository.GetPaginatedProducts().then(function(data) {
//success
$scope.productItems = data;
},
//error
function() {
alert("can't get data");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker">
<div id="productList" ng-controller="ProductController">
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th width="100%">Item ID</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in productItems">
<td>
<input type="checkbox" />
</td>
<td>{{item.ID}}</td>
</tr>
</tbody>
</table>
</div>
</div>
As #tymeJV stated in the comment, you should use $http or $resource (or restangular) to perform the data access. If you are updating values outside of Angular's framework, it has no way of knowing that data has changed. By using something like $http or $resource, Angular is aware when an event has occurred that can change values and automatically checks for updates.
Alternately, you could manually issues an $apply() to essentially handle the digest update manually (ensuring Angular goes through a digest cycle when you've changed values outside of Angular). Take a look at the documentation on $apply() at https://docs.angularjs.org/api/ng/type/$rootScope.Scope .
However, your best bet is to use the Angular approach in the first place and avoid using jQuery for this.

show 2 array through ng-repeat error

i am trying to make a table from 2 arrays in AngularJS one array contains Employees name and other array contain Services Name and rest of the cells contain check boxes but when i do i got error Error: [ngRepeat:dupes]
here is my AngularJS code
var model = angular.module('wizard', ['ngRoute'])
.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/m5", {
controller: "model5Controller",
templateUrl: "/templates/m5.html"
});
$routeProvider.otherwise({ redirectTo: '/' });
}]);
var model5Controller = ["$scope", "$http", "$window", function ($scope,
$http, $window) {
$scope.PBA = [];
$scope.SOB = [];
$http.get('/Test/GetPBA').
then(
function (result) {
//success
$scope.PBA = result.data;
},
function () {
//error
});
$http.get('/Test/GetSOB').
then(
function (result) {
//success
$scope.SOB = result.data;
},
function () {
//error
});
$scope.save = function () {
//to be written
};
}];
GetPBA/GetSOB returns JSON type Array of List
both contain properties like Id, Name
here is my html
<div>
<form ng-submit="save()">
<table border="1">
<tr>
<td><strong>Services</strong></td>
<td ng-repeat="e in PBA">{{e.Name}}</td>
</td>
<tr ng-repeat="i in SOB">
<td>{{i.Name}}</td>
<td ng-repeat="e in PBA">
<input type="checkbox" name="{{e.Id}}" />
</td>
</tr>
</table>
</form>
Try this
<tr ng-repeat="i in SOB track by $index">
<td>{{i.Name}}</td>
<td ng-repeat="e in PBA track by $index">
<input type="checkbox" name="{{e.Id}}" />
</td>
</tr>

Resources