On Checking Check Box Get the child Object Angular Js - angularjs

I want to achieve a scenario in which when i click TV1 radiobutton i want to get all of its children in the object i.e ProductName TV1, Number Of Channels 1 . Below is my code
Markup :
<div ng-repeat="product in ProductTypes">
<div ng-show="product.selected" ng-repeat="Product in product.ProductList">
<label>
<input type="radio" name="internetProduct{{$parent.$index}}"
ng-model="Product" ng-value="{{Product}}" ng-click="GetValue()" />
{{Product.ProductName}}
</label>
<table>
<tr ng-repeat="(key, val) in Product">
<td>{{key}}</td>
<td>{{val}}</td>
</tr>
</table>
</div>
</div>
Controller (js) :
var app = angular.module('ProductCatalog.controllers', ['ui.bootstrap'])
.controller('OfferCtrlr', function ($scope, $http, $modal) {
$scope.GetValue = function() {
var a = $scope.radio;
}
})
Right now, nothing is coming in $scope.radio. Please helpp.

You can pass the product instance to your ng-click function call as a parameter. So whenever the radio button is clicked, the corresponding product instance will be available inside your function. The below code will give you the instance for radio button. Do the same thing for checkbox, call a function on checking and pass the corresponding instance.(you have not provided the markup for checkbox)
HTML:
<div ng-repeat="product in ProductTypes">
<div ng-show="product.selected" ng-repeat="Product in product.ProductList">
<label>
<input type="radio" name="internetProduct{{$parent.$index}}"
ng-model="checked" ng-value="Product" ng-click="GetValue(Product)" />
{{Product.ProductName}}
</label>
<table>
<tr ng-repeat="(key, val) in Product">
<td>{{key}}</td>
<td>{{val}}</td>
</tr>
</table>
</div>
</div>
JS:
var app = angular.module('ProductCatalog.controllers', ['ui.bootstrap'])
.controller('OfferCtrlr', function ($scope, $http, $modal) {
$scope.GetValue = function(product) {
console.log(product);
}
})

Well, Load all the parent and child objects then show/hide through the AngularJS, through that you will achieve your scenario.

Related

get value from ng-repeat radio buttons

I have ng-repeat of radio buttons:
<div ng-repeat="c in currencies">
<ion-radio ng-model="checkradio" ng-value='c.code' >
{{c.name}} {{c.code}}
</ion-radio>
</div>
I intend to $watch the model and the value of the selected radio buttons:
$scope.$watch('checkradio', function () {
$scope.checkradio = "";
})
I don't get any value from my radio buttons. Obviously, I'm doing something wrong. I tried other approaches but they didn't work. Can anyone suggest how to get the value from the radio buttons?
For binding you should have an object not a variabile.
Then in your controller you should have:
$scope.radios = [{name:"first", code:"1"}, {name:"second", code:"2"}];
$scope.model = { checked: "1" };//check the first element
and in your HTML:
<ion-radio ng-repeat="radio in radios" ng-model="model.checked" ng-value="radio.code">{{radio.name}}</ion-radio>
or
<div ng-repeat="c in currencies">
<ion-radio ng-model="model.checked" ng-value='c.code' >
{{c.name}} {{c.code}}
</ion-radio>
</div>
You can find a codepen here
try this, this may help you, Here is working fiddle
<div ng-controller="MyCtrl">
<div ng-repeat="(key,val) in currencies">
<input type="radio" ng-model="$parent.checkradioasd" ng-value='val.code' >
{{val.name}}
</div> <br>
<div>Selected : {{checkradioasd}}</div>
controller
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.currencies = [{name:'Option 1',code:1},{name:'Option 2',code:2}];
$scope.checkradio = $scope.currencies[0].code;
}

NG-Repeat with NG-show Not executing with dynamic data

Im trying to get a client list and detail view to work but i cant seem to figure it out. The NG-init wont work nor will the ng-click, I can get it to work if its hard coded, but when dynamically loading data it wont work. Id appreciate if anyone can point out the correct way to execute this.
html:
<div ng-controller="ClientCtrl as clients">
<table class="listview">
<tbody>
<tr ng-repeat="stuff in clients.records">
<td><a ng-click="client = {{$index}}" class="client-link">{{stuff.first_name}} {{stuff.last_name}}</a></td>
</tr>
</tbody>
</table>
<div class="detailview">
<div ng-repeat-start="things in clients.records " ng-if="$first">
<div id="contact-{{$index}}" class="tab-pane active" ng-show="client == {{$index}}" ng-init="client = {{$index}}">
<h2>{{things.first_name}} {{things.last_name}}</h2>
</div>
</div>
<div ng-repeat-end="things in clients.records " ng-if="!$first">
<div id="contact-{{$index}}" class="tab-pane active" ng-show="client == {{$index}}" ng-init="client = {{$index}}">
<h2>{{things.first_name}} {{things.last_name}}</h2>
</div>
</div>
</div>
</div>
controller.js:
function ClientCtrl($scope,$http,$interval, $rootScope){
var ClientCtrlData = this;
$http.get("api/clients").success(function(response) {
ClientCtrlData.records = response.records;
});
var promise;
// simulated items array
$scope.items = [];
// starts the interval
$scope.start = function() {
// stops any running interval to avoid two intervals running at the same time
$scope.stop();
// store the interval promise
promise = $interval(
function(){
$http.get("api/clients").success(function(response) {
ClientCtrlData.records = response.records;
console.log("People loaded");
});
}.bind(this)
,1000000 * 10);
};
// stops the interval
$scope.stop = function() {
$interval.cancel(promise);
};
// starting the interval by default
$scope.start();
$scope.$on('$destroy', function() {
$scope.stop();
});
}
angular
.module('inspinia')
.controller('ClientCtrl',ClientCtrl)
plnkr http://plnkr.co/edit/yzN787uL6C82Z6g6JNOq
First off, no need to use ng-click="client = {{$index}}", you're already saying that the code should be parsed by angular so no need for the angular brackets {{ }}.
Second, you need to scope client inside ng-click="client = $index" for example as such ng-click="clients.client = $index", otherwise angular doesn't know where to look for the property.
I also wonder what the need for the ng-init is? I'm guessing this is just mock functionality, because now it will just set the clients.client variable for each item until it ends up being the last one in the list.
In any case, here's a version of your code with fixed syntax, you should be able to take it from here
http://plnkr.co/edit/UyKYvxpErcehizSBKaqy?p=preview
<div ng-controller="ClientCtrl as clients">
<table class="listview">
<tbody>
<tr ng-repeat="stuff in clients.records">
<td>
<a ng-click="clients.client = $index" class="client-link">{{stuff.first_name}} {{stuff.last_name}}</a>
</td>
</tr>
</tbody>
</table>
<div class="detailview">
<div ng-repeat="things in clients.records ">
<div id="contact-{{$index}}" class="tab-pane active" ng-show="clients.client == $index" ng-init="clients.client = $index">
<h2>{{things.first_name}} {{things.last_name}}</h2>
</div>
</div>
</div>
</div>

how to access data from scope object

I need to get data from $scope.List2 object:
<div ng-app="App">
<div id="firstlist" ng-controller="Controller">
<table id="requesttable" class="RequestTable">
<tr ng-repeat="item2 in List2">
<td class="selectedItem">{{item2.Title}}</td>
</tr>
</table>
<button id="Reqbutton" onclick="SendRequest()">Send</button>
</div>
</div>
The problem is that if I put SendRequest function inside controller then it cannot be called (I get "SendRequest() is not defined" message). And if I put the function outside the controller I cannot access List2.
What do I miss?
As #sp00m suggested. You should use ng-click instead of onclick on the button. The html would look like this then:
<button id="Reqbutton" ng-click="sendRequest()">Send</button>
In your controller
app.controller('testController', ['$scope', function {
$scope.list2 = [];
$scope.sendRequest = function() {
var test = $scope.list2;
...
};
}]);

Angular JS binding scope data within ng-repeat to form

I have a collection of items in $scope.data with fields "id","name" & "age", that are being displayed in the view using ng-repeat directive.
For each set of items, there is a corresponding "edit button".
I want to be able to access values for the particular set of items for which edit button was pressed.
Html:
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<form ng-submit="submit()">
<input type="text" ng-model="i.id"/>
<input type="submit" value="Edit" />
</form>
</div>
</div>
Script:
function Ctrl($scope)
{
$scope.data = [
{id:1,name:"Alex",age:22},
{id:2,name:"Sam", age:28}
];
$scope.submit = function() {
//access id of user for which edit was clicked
};
}
What is the right way to do this?
Instead of a form, I would suggest you just use a button:
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<input type="text" ng-model="i.id"/>
<button ng-click="submit(i)">Edit</button>
</div>
</div>
Just send i into the button click event (I suppose you could use form if you need validation, but your example doesn't seem to need it).
Your submit function then changes to:
$scope.submit = function(selectedItem) {
// here you now have access to selected item
};
Try this:
HTML:
<form ng-submit="submit(i.id)">
JavaScript:
$scope.submit = function(userId) {
// you have userId
};
One option is to just use an ng-click within a button that calls your submit passing in i
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<button ng-click="submit(i);">edit</button>
</div>
</div>
and the function:
$scope.submit = function(i) {
console.log(i);
//access id of user for which edit was clicked
};
Here's a fiddle of that working: http://jsfiddle.net/pRAcP/

CRUD model with nested model

I'm currently building a CRUD for my app admin. I'm using AngularJS with a RESTfull API.
I can sucessfully save a simple model. But when I have Many-to-many relationship I'm a bit lost when it comes to set the update/create form.
I have build a Plunker to showcase the attempt:
http://plnkr.co/edit/okeNuYBJ5f33gtu6WBoW
EDIT:
Now using checkbox instead of dropdown as Jason suggested:
http://plnkr.co/edit/okeNuYBJ5f33gtu6WBoW
But my problem #3 is still not fixed. How can I save those updated/created relationships?
So I have that User model that has a Many-to-Many relationship with a Role model. I am able to display/list the model with its relationship. When editing a User I load all Roles so UI can build a dropdown of Roles to be selected. I want to have as many dropdown as there is a relationship. So I nested my dropdown in a repeat="userRole in user.role".
When doing an update
First problem: if a user has many roles it display as many dropdown as there is but the selected role for each one is the first relationship.
Second problem: I have a button to add a new role to the loaded user. I'm not sure I made it right since when saving I don't see any trace of the new attached role.
Third problem: when saving I loose the connection from my roles. Only the user is updated. My form is wrong but where is the problem?
When doing a create
I'm not able to link a role to a new user. When I clic on "Add a new role" the first role of the Roles list is pushed to the user. But user is not yet created. So I get an error. Once again my form is wrong. What is the error?
When saving a new user how can I also POST the related roles?
Here is some code in case the Plunker doesn't work:
index.html
<!DOCTYPE html>
<html lang="en" xmlns:ng="http://angularjs.org" data-ng-app="CRUD">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css" />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css" />
</head>
<body>
<div class="span6" ng-view></div>
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<script src="http://code.angularjs.org/1.1.0/angular-resource.js"></script>
<script src="/crud.js"></script>
</body>
</html>
crud.js My AngularJS specific code
var users = [
{'id':1,'name':'User 1', 'role':[{'id':1,'name':'Role 1'},{'id':2,'name':'Role 2'}]},
{'id':2,'name':'User 2', 'role':[{'id':2,'name':'Role 2'}]},
{'id':3,'name':'User 3', 'role':[{'id':1,'name':'Role 1'}]},
{'id':4,'name':'User 4', 'role':[{'id':3,'name':'Role 3'},{'id':2,'name':'Role 2'}]}
];
var roles = [
{'id':1,'name':'Role 1'},
{'id':2,'name':'Role 2'},
{'id':3,'name':'Role 3'}
];
/* Route */
angular.module('CRUD', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/create', {templateUrl: 'create.html',controller: ctrlCreate}).
when('/read', {templateUrl: 'read.html',controller: ctrlRead}).
when('/update/:userId', {templateUrl: 'update.html', controller: ctrlUpdate}).
otherwise({redirectTo: 'read'});
}]);
/* Controller CREATE */
function ctrlCreate($scope, $http, $location) {
// dirty hack to find the user to update (in real life it would be loaded via REST)
$scope.user = null;
$scope.roles = roles;
$scope.save = function() {
// dirty hack to change the user (in real life it would be trigger a POST request to the server with updated model)
users.push($scope.user);
//if a scope digestion is already going on then it will get picked up and you won't have to call the $scope.$apply() method
if(!$scope.$$phase) { //this is used to prevent an overlap of scope digestion
$scope.$apply(); //this will kickstart angular to recognize the change
}
$location.path('/');
};
$scope.addRole = function(){
$scope.user.role.push(roles[0]);
};
}
ctrlCreate.$inject = ['$scope','$http','$location'];
/* Controller READ */
function ctrlRead($scope, $http, $location) {
// dirty hack to find the user to update (in real life it would be loaded via REST)
$scope.users = users;
$scope.roles = roles;
}
ctrlRead.$inject = ['$scope','$http','$location'];
/* Controller UPDATE */
function ctrlUpdate($scope, $http, $location, $routeParams) {
$scope.user = null;
$scope.roles = roles;
var id=$routeParams.userId;
// dirty hack to find the user to update (in real life it would be loaded via REST)
for (var i = 0; i < users.length; i++) {
if (users[i].id==id) {
$scope.user=users[i];
console.debug($scope.user.role);
}
}
$scope.save = function() {
// dirty hack to change the user (in real life it would be trigger a PUT request to the server with updated model)
for (var i = 0; i < users.length; i++) {
if (users[i].id==id) {
users[i] = $scope.user;
}
}
//if a scope digestion is already going on then it will get picked up and you won't have to call the $scope.$apply() method
if(!$scope.$$phase) { //this is used to prevent an overlap of scope digestion
$scope.$apply(); //this will kickstart angular to recognize the change
}
$location.path('/');
};
$scope.addRole = function(){
$scope.user.role.push(roles);
console.debug($scope.user.role);
};
}
ctrlUpdate.$inject = ['$scope','$http','$location', '$routeParams'];
Now my templates:
create.html
<form>
<div class="control-group">
<label class="control-label">Name</label>
<input type="text" ng-model="user.name" placeholder="Enter a name here">
</div>
<div ng-repeat="userRole in user.role">
<div class="control-group">
<label class="control-label">Role</label>
<select ng-selected="userRole.id">
<option ng-repeat="role in roles" value="{{role.id}}">{{role.name}}</option>
</select>
</div>
</div>
<button ng-click="addRole()">Attach another role</button>
<br />
<br />
<input type="submit" value="Submit" ng-click="save()" class="btn btn-primary">
Cancel
</form>
read.html
<br />
<table class="table table-bordered table-striped table-centred table-condensed table-hover">
<thead>
<tr>
<th>User Name</th>
<th>Role Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.name}}</td>
<td>
<span ng-repeat="role in user.role">{{role.name}}</span>
</td>
<td>
<a title="edit" href="#/update/{{user.id}}"><i class="icon-edit"></i></a>
</td>
</tr>
</tbody>
</table>
<br />
<i class="icon-plus"></i> Create a new user
update.html
<form>
<div class="control-group">
<label class="control-label">Name</label>
<input type="text" ng-model="user.name" placeholder="Enter a name here">
</div>
<div ng-repeat="userRole in user.role">
<div class="control-group">
<label class="control-label">Role</label>
<select ng-selected="userRole.id">
<option ng-repeat="role in roles" value="{{role.id}}">{{role.name}}</option>
</select>
</div>
</div>
<button ng-click="addRole()">Attach another role</button>
<br />
<br />
<input type="submit" value="Submit" ng-click="save()" class="btn btn-primary">
Cancel
</form>
Please made advice if you see some bad coding or wrong architecture (I think I could do some directive for instance when it comes to add a new role maybe?). I hope this is clear enough.
Thanks!
You can solve the first 2 problems you are having by redesigning your UI. Instead of using dropdowns use a checkbox field. Example plnkr:
http://plnkr.co/edit/hgq2hmbRty7B9oryQnkm
Once you have less moving parts on your page, hopefully it will be easy to debug the 3rd problem.

Resources