Save items from controller into array on Yes / No basis - javascript

Having some trouble with angularJS i've only been working with it for two weeks and my javascript knowledge aswell is rather no existent so please take this into account.
Im currently making a hearing test app which all functionality is working apart from a reporting system im building into it.
Im wanting on a yes / no basis record at what frequency and DB they heard the sound from these two buttons.
<button ng-click='' type="button" class="btn btn-primary btn-lg glyphicon glyphicon-ok"></button>
<button ng-click='' type="button" class="btn btn-default btn-lg glyphicon glyphicon-remove"></button>
Here is an example of one of my controllers for 125HZ at 0DB as an example.
// 125 FREQUENCY START
myApp.controller('125Zero', ['$scope','ngAudio', function($scope, ngAudio) {
$scope.title = "Frequency: 125Hz";
$scope.frequency = "0Db";
$scope.sound = ngAudio.load("audio/125_0.mp3"); // returns NgAudioObject
$scope.previous =""
$scope.next ="125Ten"
}]);
Im wishing to record the $scope.title and $scope.frequency attribute into and array for later processing.
this is as far as ive got with the idea
function result() {
$scope.results = [];
$scope.resultService = function(){
$scope.results.push();
}
}
with no results, i want to save both title and frequency into the array, and allow the program to move onto the next controller and do the same if the frequency is heard.
Thanks for any help or ideas.
Apologies if my code isn't the cleanest or ideal but as i explained this is my second week working with AngularJS
Thanks.

Add event listeners to the buttons:
<button ng-click='buttonPressed('okay")' type="button" class="btn btn-primary btn-lg glyphicon glyphicon-ok"></button>
<button ng-click='buttonPressed("remove")' type="button" class="btn btn-default btn-lg glyphicon glyphicon-remove"></button>
In your controller, add those methods:
myApp.controller('125Zero', ['$scope','ngAudio', function($scope, ngAudio) {
$scope.title = "Frequency: 125Hz";
$scope.frequency = "0Db";
$scope.sound = ngAudio.load("audio/125_0.mp3"); // returns NgAudioObject
$scope.previous ="";
$scope.next ="125Ten";
$scope.buttonPressed= function(outcome) {
$scope.result = [];
var tempObj = {};
tempObj.title = $scope.title;
tempObj.frequency = $scope.frequency;
// check for outcome to find out if it's okay or remove.
//based on that set the frequency here.
$scope.result.push(tempObj);
// add this to service
}
}]);
To get this value in next controller:
You need to store that $scope.result inside a service. So create a service and push the $scope.result into that.
In your second controller, inject that service as a dependency and access the value there.

Related

ng-model not binding to input data within ng-repeat

Using AngularJs 1.6.7, I have created a table which pulls project details from a database and displays these details within a table. Each row has a modify/update button using ng-show/hide. When modify is clicked, the div changes to editable input fields, when update is clicked, the new input data will be update in the database.
I am trying to access input items within an ng-repeat and using ng-model to bind the input to update projects in a database using Flask.
The problem is that when I access the data in AJS once update is clicked, no data has binded to the new input values.
My HTML looks like this.
<tr data-ng-repeat="(key, value) in projects" >
<td>
<div data-ng-hide="edditable_project[value.project_name]">{[value.project_name]}
</div>
<div data-ng-show="edditable_project[value.project_name]">
<input class="form-control" data-mg-model="updatedProjectName" value="{[value.project_name]}">
</div>
</td>
<td>
<button class="btn btn-danger add-on pull-right btn-sm" data-ng-click="removeProject(value)">Delete</button>
<button class="btn btn-primary add-on btn-sm pull-right" data-ng-hide="edditable_project[value.project_name]" data-ng-click="modify(value.project_name)">Modify</button>
<button type="submit" class="btn btn-success pull-right btn-sm " data-ng-show="edditable_project[value.project_name]" data-ng-click="update(value)">Update</button>
</td>
</tr>
And my controller looks like this:
app.controller('projectSettingsController', ['$scope', '$http', function($scope, $http) {
$scope.modify = function(project) {
$scope.edditable_project[project] = true;
};
$scope.update = function(project) {
data = {
project_name: $scope.updatedProjectName,
}
console.log($scope.updatedProjectName);
// Update project.
$http.post('/api/project/update-project', data).then(function(response) {
toastr.success(response.data);
});
$http.get('/api/project/get-all-project-details').then(function (response) {
$scope.projects = response.data;
});
$scope.edditable_project[project] = false;
};
}]);
The current output for ng-model="updatedProjectName" is undefined.
Am I doing something wrong within the scope?
well you should define your binding vairable in the scope of your controller like
$scope.updatedProjectName =""; by default it`s null as you have described, but for all your inputs you will have one data binding, i think you should have some
$scope.data={};
tr data-ng-repeat="(key, value) in projects" >
<input data-ng-model="data[key]">
</tr>
and you don`t need to set value in your input, ng-model will make it for you
You are trying to access a variable which is defined inside of ng-repeat's scope. What you would want to do in this case is pass value and work on the project variable inside the update function.
Change your mark up to data-mg-model="value.project_name". Now the ng-model binds to same. When the update completes set the latest data(if needed) as properties on project. It will reflect in the view because of 2 way data binding
Inside update you should do as follows
$scope.update = function(project) {
// Update project.
$http.post('/api/project/update-project', project).then(function(response) {
toastr.success(response.data);
// If needed set new properties on the project variable
// based on the response
});
}
You seem to have a typo:
<input class="form-control" data-mg-model="updatedProjectName" value="{[value.project_name]}">
Use ng-model instead of mg-model.

simple Previous/Next buttons

I'm triying to paginate the response of an API. This API, have 15 items per page.
Actualy, i'm using something like this:
vm.next = function(currentPage){
$http.get('/api?page='+vm.firstPage++)
.then(function(data){
vm.chuck = data.data.Response;
});
}
vm.previous = function(currentPage){
$http.get('/api?page='+vm.firstPage--)
.then(function(data){
vm.chuck = data.data.Response;
});
}
and
vm.firstPage = 1;
My html view for buttons:
<div class="text-center">
<button type="button" class="btn btn-warning" ng-click="$ctrl.previous()">Previous</button>
<button type="button" class="btn btn-warning" ng-click="$ctrl.next()">Next</button>
</div>
The idea was to had the increment/decrement on every click. It works, but only after the second click. Also, if i change the value of vm.firstPage to 2, it works since the very first click, but when i click Previous, it becomes a mess.
What can i do to have the increment/decrement on the buttons?
I'm using AngularJs and javascript
I think it's about the operator precedence. Make vm.firstPage++/vm.firstPage-- before API call
vm.next = function(currentPage){
vm.firstPage++;
$http.get('/api?page='+vm.firstPage)
.then(function(data){
vm.chuck = data.data.Response;
});
}

Unable to validate mutli-select input with AngularJS

I'm new to Angular, and I struggle with validating a multi select input with ngOptions attribute.
I want the field to be required, so the user must chose at least one option. However the validation methods Angular have simply doesn't work in my case, Here's what I've tried:
<form name="products" novalidate>
<div class="form-group">
<label for="select-product">Chose product/s</label>
<select id="select-product" name="selectedProduct" class="form-control"
required
multiple
ng-model="selectedProduct"
ng-options="product.name for product in products">
</select>
</div>
<button class="btn btn-primary pull-left" ng-click="products.selectedProduct.$valid && goToChildrenId()">Next</button>
</form>
Even if I chose a product and I can see that the form class switch from .ng-invalid to .ng-valid, the function goToChildrenId() doesn't run.
Also, if I add {{products.selectedProduct.$valid}} at the bottom, when I refresh the page I can see "false" for a second but it disappear, why?
If it's relevent, this is the controller:
adminCheckout.controller('productsCtrl', function($scope, $http, wpMiniapps, $location, $rootScope){
$scope.products = [];
var url = wpMiniapps.routeUrl("getProducts");
$http.post(url, {}).then(function(res){
$scope.products = res.data.data;
}, function(err){
console.log(err);
});
$scope.$watch('selectedProduct', function (newVal) {
$rootScope.globalData.products = newVal;
});
$scope.goToChildrenId = function(){
$location.path('/select-children');
};
});
I searched the web but nothing seems to work in my case.
I will really appreciate any help.
You have a variable name collision which is causing the problem: the form is named products and this ends up as a $scope variable. But it collides with $scope.products = [] from the controller. Simply renaming the form to, e.g., productsForm solves the problem:
<form name="productsForm" novalidate>
...
<button class="btn btn-primary pull-left" ng-click="productsForm.selectedProduct.$valid && goToChildrenId()">Next</button>
</form>

AngularJS and MVC routing problems

I am having some problems with my routing.
My HomeController (ASP) Has few ActionViews Index - displays list of products,
Add, Edit, Delete.
Edit Action of course takes me to the EditView. So far so good.
Problem is that in this view angular kickes in (I am passing asp mvc model to angular in ng-init).
ng-controller="routeEditCtrl" data-ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))"
Then after edit controls I have Save and cancel button defined as follows:
<button class="btn btn-success" ng-click="validateAndSubmit()"><i class="fa fa-edit"></i> Save</button>
<i class="fa fa-trash"></i> Cancel
The cancel button works fine. However the angular controller methods does not work that nice.
$scope.validateAndSubmit = function () {
//var result = $scope.ctrlCode.validate();
if (true) {
$http.post("SaveRoute", $scope.model).success(function (data) {
$scope.model = data;
$location.path("Index");
}).error(function (data) {
});
}
}
}]);
On successful post I wanted go back to Index view.
How can I archive that?

Getting selected option in AngularJS

I am generating a thumbnail list of photos (using ng-repeat), and under each one of these photos I have two buttons, one to view more details and another to purchase.
I am finding a problem how to map the buttons. Basically I want that when a user clicks on the purchase button underneath Photo A, in the booking form (which is a different view), he/she will see the details pertaining to Photo A, rather than having the user select the photo again from some drop down. The list of photos is coming from a JSON string.
Mainly the difficulty I am finding is how to pass the details of which button was clicked to the booking view so that I would be able to display the details of the selected photo immediately.
I am new to AngularJS and am not sure if there is a simple way that can be done.
My HTML is this:
<div class="col-md-4 ng-scope" ng-repeat="photo in photos">
<div class="thumbnail">
<img src="{{photo.thumbnail}}" alt="{{photo.title}}">
<div class="caption">
<h4 class="ng-binding">{{photo.title}}</h4>
<p><button type="button" class="btn btn-default">Photographer</button><br ><button type="button" class="btn btn-default">Purchase</button></p>
</div>
</div>
Angular JS:
App JS
angular
.module('app', [
'ui.router'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('photos', {
url: '/photos',
templateUrl: 'templates/photos.html',
controller: 'photosCtrl',
resolve: { photos: ['$http', function($http){
return $http.get('api/photos.json').then(function(response){
return response.data;
});
}]}
})
}]);
photosCtrl JS:
angular
.module('app')
.controller('photosCtrl', ['$scope', 'photos', function($scope, photos) {
$scope.photos = photos;
}]);
using ngClick directive is a good idea as #Ashesh suggested
Assuming the JSON containing your photos comes with a bunch of photo object, I'd rather add two functions to the scope of photosCtrl like this:
angular.module('app')
.controller('photosCtrl', ['$scope', 'photos', function($scope, photos) {
$scope.photos = photos;
$scope.showDetailsOf = function(photo) {
// photo argument is the actual object of which 'details' button was pressed
// coming from the ngRepeat in your template example
console.log('show details of ' + photo.title);
}
$scope.purchase = function(photo) {
// same as above
console.log('purchase ' + photo.title);
}
}]);
The template should look like this:
<button type="button" class="btn btn-default" ng-click="showDetailsOf(photo)">Details</button>
<button type="button" class="btn btn-default" ng-click="purchase(photo)">Purchase</button>
Furthermore you can factor this logic out to e.g. a photoService so that your controller won't contain business logic which is always preferable as both of your controller and the service can be covered by tests more easily, because you decouple them. Hope this helps.
Use ngClick:
<p><button type="button" class="btn btn-default" ng-click="photo.showPhotographer()">Photographer</button><br ><button type="button" class="btn btn-default" ng-click="photo.buy()">Purchase</button></p>
And ofcourse, photo.showPhotographer() etc. can do what you like them to do:
function Photo() { // the photo object
this.buy() {
// api call to buy with the id of the photo or window.navigate('buy_url?id=' + this.id), etc.
}
}

Categories

Resources