I have a list of dynamically generated radio boxes in html:
**index.html**
<div id="choiceGraphId1" class="radio-button" ng-controller="selectGraph1">
<div ng-repeat="choice1 in choices1">
<table>
<label class="labelClass" > <td > {{choice1.graphChoice1}} </td> </label> <td>  </td> <label class="labelClass" > <td> <input type="radio" ng-model="$parent.selectedGraph1" ng-value="choice1.graphChoice1" name="graphChoice1" required /> </td> </label></table></div></div>
Angular Controller:
app.controller('selectGraph1', function ($scope,$rootScope) {
$rootScope.selectedGraph1="Choice1";
$rootScope.choices1 = [{
graphChoice1: "Choice1"
}, {
graphChoice1: "Choice2"
}
];
alert($rootScope.selectedGraph1);
});
I want to pass the value of $rootScope.selectedGraph1 to
PrintReportToPDF controller :
**index.html**
<div class="buttonsClass" ng-controller="**PrintReportToPDF**">
<button popover="Click button to open selected date range PDF Report in a new tab"
popover-trigger="mouseenter" type="button" class="btn btn-info"
ng-disabled="dataLoading"
ng-click="PrintReportToPDF()">
<i class="fa fa-file-pdf-o icon"></i>
Preview PDF Report
</button>
...
app.controller('PrintReportToPDF', function($scope, $rootScope, $window, UrlServices , StatsByDatePDF, StatsByDateExcel, Flash) {
//Preview PDF Report
alert($rootScope.selectedGraph1);
alert($rootScope.selectedGraph2);
$scope.PrintReportToPDF_1_StatisticsByDate = function() {
....
I am trying to access the $rootScope.selectedGraph1 in my controller
but its value is undefined in PrintReportToPDF controller.
What am I doing wrong here?
You can find your solution here
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
return {
name : 'anonymous'
};
});
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
}
Related
So, I am creating a web app, where one page I have a user list and on the second page, I have the users details page. On the second page, I have a confirm button where I want to remove that user when the "Confirm" button is clicked with a 200 Status code. However, I am getting a DELETE : 405 (Method Not Allowed). So, here is my code down below. Please tell me or help me fix this problem. Thank you in advance.
Here is my code.
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<button class="btn btn-primary" ng-click="doDelete(id)">Confirm</button>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
</fieldset>
</form>
</div>
</div>
</div>
Services
app.factory('people', function ($http) {
var service = {};
service.getUserInfo = function () {
return $http.get('https://api-dev.mysite.io/admin/v1/unconfirmed_lawyers');
};
service.confirmUser = function (lawyerId) {
return $http.put('https://api-dev.mysite.io/admin/v1/lawyers/{lawyerId}/confirm');
};
return service;
});
LawyerController
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
$scope.lawyerId = $routeParams.id;
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
});
}]);
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
}, function (error) {
console.log(error)
});
}
});
App.js
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1);
location.href = '#/lawyer';
};
If you changed your HTML, so you passed the person instead.
<button class="btn btn-primary" ng-click="doDelete(person)">Confirm</button>
You can use this to find the index within the lawyers, then remove it.
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1)
};
The issue is your are using $http.delete which performs an HTTP Delete request. This doesn't sound like something you intended.
I have a select box. I want to generate the same on a 'Add New' button click.
View
<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="Get_toolNames()">Add New
<i class="fa fa-plus"></i>
</button>
<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name" ng-options="t.tm_id as t.tm_name for t in tools" required>
<option value="">Select</option>
</select>
How can I generate the same on this button click?
If you have
<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="buttonClick"> Add New
<i class="fa fa-plus"></i>
</button>
In your controller you can inject and use $compile service.
$scope.buttonClick = function(){
var el = angular.element(/* Here your element */);
el.append( '<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name" ng-options="t.tm_id as t.tm_name for t in tools" required>' +
'<option value="">Select</option>' + '</select>')
$compile(el)($scope);
}
Change your logic to get the data and the element you want:
For more see $compile.
Update
var sample_2_tbody = angular.element('#sample_2 tbody');
$compile(sample_2_tbody)($scope);
How to inject a service in the controller:
app.controller('MyController', ['$scope', '$compile', function($scope, $compile){
}])
In AngularJS views are just a model reflection and their scope is only for data presentation. That's mean you never need to manually copy a DOM Element, you just need to operate on the bound model.
function TestCtrl($scope, select) {
copy = () => angular.copy(select);
$scope.selects = [copy()];
$scope.values = {};
$scope.add = () => {
//$scope.selects.unshift(select); // add at the beginning
$scope.selects.push(copy()); // add at the end
};
}
angular
.module('test', [])
.value('select', [{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
subItem: { name: 'bSubItem' }
}])
.controller('TestCtrl', ['$scope', 'select', TestCtrl])
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<button ng-click="add($event)">Add</button>
<hr>
<div ng-repeat="select in selects track by $index">
<select ng-model="values[$index]" ng-options="t as t.label for t in select">
</select>
</div>
<hr>
<pre><code ng-bind="values | json"></code></pre>
</article>
</section>
I have a form, when I submit it, it pushes some object to my array. Beneath that form I have a table that shows all items in that array. I want my table to update automatically (without refreshing the page) when new item pushed.
Submit button:
<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>
In my controller:
$scope.updateTable = function() {
setTimeout(function () {
$scope.$apply();
$scope.$digest();
}, 0);
};
However, it does not work.
I tried different approaches like $watch service, but i`ve got the same result.
Table
<div class="row paytable">
<div class="col-xs-10 col-xs-offset-1">
{{payments.length}}
<table class="table table-hover ">
<tr>
<td>Id</td>
<td>Amount</td>
<td>Cause</td>
</tr>
<tr ng-repeat="item in payments">
<td>{{item.id}}</td>
<td>{{item.amount}}</td>
<td>{{item.cause}}</td>
</tr>
</table>
</div>
</div>
Controller
app.controller('mainController', [ 'user', '$rootScope', '$scope', 'payment', '$timeout', function(user, $rootScope, $scope, payment, $timeout) {
user.getUsers();
user.newUser();
$rootScope.currentUser = user.currentUser();
$scope.payments = payment.getPayments();
$scope.newPayment = payment.newPayment;
$scope.updateTable = function() {
setTimeout(function () {
console.log('apply ------------');
$scope.$apply();
$scope.$digest();
}, 0);
};
$scope.showPayMessage = function() {
console.log('im here');
$scope.showSM = true;
$timeout(function() {
$scope.showSM = false;
}, 2000);
};
}]);
payment - my service for array manipulation.
Form
<div class="newpay row" >
<div class=" col-xs-10 col-xs-offset-1">
<h1>Hello, {{currentUser.name}}</h1>
<h4 ng-show="showSM" class="bg-success">Payment confirmed</h4>
<form name="inputform" ng-submit="newPayment(amount, cause); showPayMessage();">
<div class="form-group">
<label for="exampleInputEmail1">Amount</label>
<input type="number" name="amount" ng-model="amount" class="form-control" id="exampleInputEmail1" placeholder="Amount" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Cause</label>
<input type="text" name="cause" ng-model="cause" class="form-control" id="exampleInputPassword1" placeholder="Cause" required>
</div>
<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>
</form>
</div>
</div>
payments: {{payments.length}}
<payments-table payments="payments"></payments-table>
To display that table I created directive.
$scope.$apply and $scope.$digest are better suited for working with 3rd party libraries or testing. In your case Angular is well aware to your changes. The thing is, your payments array, that resides in a service should be queried again after submitting a new item (unless you have a direct reference to the array, then no query should be made).
Like this:
View
<form name="inputform" ng-submit="onSubmit()">
Controller
$scope.onSubmit = function() {
newPayment($scope.newItemAmount, $scope.newItemCause); // Assuming they are properties in the controller
showPayMessage();
$scope.payments = payment.getPayments(); // getting the updated array
}
Consider the following JS
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}
);
And the following HTML
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
My problem is that when the page loads, "test" is written in the text field, but when I change the field or press the button, nothing happens (console says "test" on every change or button click. Anyone know what I did wrong?
Try to wrap the value in an object. Objects are passed by reference, but simple values are passed as a copy of that value. It happened to me too several times.
Try this approach
$scope.myObject.searchBooking = "test"
So the full code will look like this
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.myObject.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.myObject.searchBooking);
//$location.path('/bookings/' + $scope.myObject.searchBooking);
//delete($scope.myObject.searchBooking);
}
$scope.printValue = function() {
console.log($scope.myObject.searchBooking);
}
}
);
and the html
<input type="text" class="form-control" placeholder="Testing" ng-model="myObject.searchBooking" ng-change="printValue()">
Find this fiddle which is having ng-model binding in ng-change.
HTML
<div ng-controller="MyCtrl">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
Angular controller
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}
I have an AngularJS app with a list of users with an 'Edit' button beside each user. Each user has a number of subjects associated with them. When I click on 'Edit', it opens a form in which you can edit user details, and select associated subjects from a list of checkboxes. I'm trying to figure out how to bind the subject checkboxes so that the subjects which the
user is already associated with are checked, and the rest are unchecked. Any suggestions appreciated.
My HTML:
<form name="UserEditForm">
Name: <br /> <input type="text" name="name" ng-model="user.name"> <br />
{{name}}
Email: <br /> <input type="text" name="name" ng-model="user.email"> <br />
{{email}}
<div class="control-group">
<label class="control-label" for="inputSubjects">Subjects:</label>
<div class="form-group">
<label ng-repeat="subject in subjects" class="checkbox">
<input type="checkbox" ng-checked="{user.subjects}" name="selectedSubjects[]" value="{{subject.id}}" ng-model="subject.selected"> {{subject.name}}
</label>
</div>
<br />
<a ng-click="updateUser()" class="btn btn-small btn-primary">Save Changes</a>
</form>
My UserEditCtrl:
angular.module('myApp.controllers')
.controller('UserEditCtrl', ['$scope', '$routeParams','SubjectsFactory', 'UserFactory', '$location',
function ($scope, $routeParams, SubjectsFactory, UserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
$scope.user.subjects = $scope.selection;
UserFactory.update($scope.user);
$location.path('/users');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/users');
};
$scope.user = UserFactory.show({id: $routeParams.userid});
$scope.subjects = SubjectsFactory.query();
$scope.selection = [];
// helper method
$scope.selectedSubjects = function selectedSubjects() {
return filterFilter($scope.subjects, { selected: true });
};
// watch subjects for changes
$scope.$watch('subjects|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (subject) {
return subject.id;
});
}, true);
}]);
As #jkinkead said, your code looks good, I fixed the ng-checked binding in accordance with your ng-model expression
Here's a simplified plunker : http://plnkr.co/edit/qaIBExtVbNdSXlQlbMym?p=preview
EDIT 1: I edited and improved the plunker to get closer to your case.