I have tried to parse my JSON data to angular js app but parsing is not working on my wamp server.
When I click the submit button on login page, there is no response. Please advise where I made mistake in my code.
Controller.js:
var app = angular.module("empApp", []);
app.controller("emp", ['$scope', 'empService', function($scope, empService){
$scope.doSearch = function(){
empService.findEmployeeById($scope.searchEmpno, function(r){
$scope.empno = r.empno;
$scope.ename = r.ename;
$scope.edept = r.edept;
$scope.esal = r.esal;
});
};
}]);
app.service("empService", ['$http', '$log', function($http, $log){
this.findEmployeeById = function(empno, cb){
$http({
url: 'http://localhost/',
method: 'GET'
})
.then(function(resp){
cb(resp.data);
}, function(resp){
$log.error('Error occurred');
});
};
}
}]);
app.directive('empDetails', function(){
return {
templateUrl: 'emp-details.html'
}
});
HTML
<body ng-app="empApp">
<div class="container-fluid">
<div ng-controller="emp">
<form class="form-inline">
<div class="form-group">
<label>Enter Employee No:</label>
<input type="text" name="name" class="form-control" ng-model="searchEmpno"/>
</div>
<div>
<button type="button" class="btn btn-primary" ng-click="doSearch()">Click</button>
</div>
</form>
<hr>
<div emp-details ng-if="empno != undefined">
</div>
</div>
</div>
</body>
emp-details.html
<div class="panel panel-primary">
<div class="panel-heading">
<h3>Employee details</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-4"><strong>Employee No</strong></div>
<div class="col-sm-7">{{empno}}</div>
</div>
<div class="row">
<div class="col-sm-4"><strong>Name:</strong></div>
<div class="col-sm-7">{{ename}}</div>
</div>
<div class="row">
<div class="col-sm-4"><strong>Department:</strong></div>
<div class="col-sm-7">{{edept}}</div>
</div>
</div>
</div>
JSON:
{
"employee":{ "empno": 251, "name":"John", "age":30, "edept":"New York" }
}
Most of the issues are related to project structure and file organization.
I would recommend reading johnpapa-angular-styleguide for properly organizing and coding an angularJS application.
There are multiple changes needed.
You're not referencing your Controller.js file.
There is an additional } is there in your service
There is no file like data.json. You will need to create that file and reference it in your service.
$http({
url: 'data.json',
method: 'GET'
})
In your service you are returning resp.data. It should be resp.data.employee.
cb(resp.data.employee);
When you are referencing paths you should use relative URL.
See the working plnkr
Couple of this:
Change your URL from 'http://localhost/' to 'data.json'
In the callback, change resp.data to resp.data.employee. This will make sure you directly get access to the employee data.
Let me know if this helps.
Controller.js
$scope.doSearch = function(employeeN){
empService.findEmployeeById(employeeN)
.then(function(r){
$scope.empno = r.empno;
$scope.ename = r.ename;
$scope.edept = r.edept;
$scope.esal = r.esal;
});
};
Service
this.findEmployeeById = function(empno){
$http({
url: 'http://localhost/data.json',
method: 'GET'
})
.then(function(resp){
return resp.data.employee;
}, function(resp){
$log.error('Error occurred');
});
};
HTML
<div>
<button type="button" class="btn btn-primary" ng-click="doSearch(searchEmpno)">Click</button>
</div>
Related
I am trying to make a UI using list of product in a json(products.json) file on local and their availability in number from wp rest api call back in html(ionic) I have this:
Controller:
.controller('ShopCtrl', function($scope, $ionicActionSheet, BackendService, CartService, $http, $sce ) {
$scope.siteCategories = [];
$scope.cart = CartService.loadCart();
$scope.doRefresh = function(){
BackendService.getProducts()
.success(function(newItems) {
$scope.products = newItems;
console.log($scope.products);
})
.finally(function() {
// Stop the ion-refresher from spinning (not needed in this view)
$scope.$broadcast('scroll.refreshComplete');
});
};
$http.get("http://example.com/wp-json/wp/v2/categories/").then(
function(returnedData){
$scope.siteCategories = returnedData.data;
console.log($scope.siteCategories);
}, function(err){
console.log(err);
});
Template view:
<div ng-repeat = "product in products">
<div class="item item-image" style="position:relative;">
<img ng-src="{{product.image}}">
<div ng-repeat = "siteCategory in siteCategories">-->
<button class="button button-positive product-price" ng-click="addProduct(product)">
<p class="white-color product-price-price">post <b>{{siteCategory[$index].count}}</b></p>
</button>
</div>
</div>
<div class="item ui-gradient-deepblue">
<h2 class="title white-color sans-pro-light">{{product.title}} </h2>
</div>
<div class="item item-body">
{{product.description}}
</div>
</div>
so how can I achieve that? I tried to use nested ng-repeat but it didn't work out.
I am trying to retrieve data from the database using jsonRpc using odoo api but i got the erro like "HTTP/1.1 GET /projects" - 404 Not Found"
here is my code snnipet
python script which is used to manipulate the data
class projects:
def GET(self):
print("get")
data=[]
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
web.header('Content-Type', 'application/json')
auth = web.input()
print(auth)
odoo = odoorpc.ODOO('field.holisticbs.com',port=8069)
odoo.login('field.holisticbs.com','info#holisticbs.com','admin')
Project = odoo.execute('project.task','search_read',[[['company_id', '=', int(auth.company)],['user_id','=',int(auth.user)]]])
return json.dumps(Project)
controller.js
controller('projectCtrl',function ($scope,API,$localStorage,localStorageService) {
// body...
console.log("Project ctrl");
API.showLoad();
var resource = "projects";
API.getData(resource, localStorageService.get('user')).then(function(data) {
// console.log("quotation"+data);
console.log(data);
$scope.projects = data;
}).catch(function(data, status) {
alert("error in request");
//console.error('GET Orders error', response.status, response.data);
}).finally(function() {
console.log("finally finished projects");
API.hideLoad();
});
})
service.js
function getDetails(resource,data) {
console.log(resource);
console.log(data);
var request = $http({
method: "get",
url: backend+resource,
params: {instance: data.inst, user:data.user, company:data.company}
});
return(request.then( handleSuccess, handleError ));
}
project.html(view page which display blank)
<ion-view view-title="Projects">
<ion-content>
<ion-list>
<div class="card" ng-contoller="projectCtrl">
<a class="button button-icon" href="#/app/newProject">
<button class="button button-positive">Create Project</button> </a>
<h2> project </h2>
<ion-item ng-repeat="proj in projects" href="#/app/projects/{{proj.id}}">
<h2 class="padding">{{proj.id}}. {{proj.name}}</h2>
<div class="row" ng-if="proj.partner_id[1]">
<span class="col col-25">Customer:</span>
<span class="col">{{proj.partner_id[1]}}</span>
</div>
<div class="row" ng-if="quot.date_order">
<span class="col col-25">Date:</span>
<span class="col">{{proj.date_order}}</span>
</div>
<div class="row" ng-if="quot.state">
<span class="col col-25">Status:</span>
<span class="col">{{proj.state}}</span>
</div>
</ion-item>
</div>
</ion-list>
</ion-content>
</ion-view>
just a silly mistake annoying me. not specified in url for routing
urls = (
'/products', 'products',
'/projects', 'projects',
'/product/(.+)', 'product'
)
$scope doesn't seems to sync with updates in Angularjs.
I update my time values (myst and myet) using ui.bootstrap.timepicker, then when I display userscheds[index] using alert(JSON.stringify($scope.userscheds[index]));, only the original values are displayed. Something I'm missing?
Any help would be appreciated
See my plunker or code below
update #1
Comment from #dgig to remove this. in ng-model="this.myst". Changed to ng-model="myst"
But my $scope still not shown with the updates done
html modal
<div class="container" ng-app="appUserSchedule">
<div ng-controller="CtrlUserSchedule" >
<div class="row">
<ul>
<li ng-repeat="x in userscheds">{{x.week_day}} {{x.time_start}}-{{x.time_end}}
<span ng-click="ctrl.showModal($index)" style="cursor:pointer;">Edit</span>
<span ng-click="ctrl.removeItem($index)" style="cursor:pointer;">Delete</span>
</li>
</ul>
</div>
<!-- Modal -->
<script type="text/ng-template" id="modalContent.html">
<div class="modal-body">
<div class="row">
<div class="col-sm-6">
<timepicker ng-model="myst" hour-step="1" minute-step="15" show-meridian="true"></timepicker>
</div>
<div class="col-sm-6">
<timepicker ng-model="myet" hour-step="1" minute-step="15" show-meridian="true"></timepicker>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="$close()">OK</button>
<button class="btn btn-primary" ng-click="saveUserScheduleEntry()">Save</button>
</div>
js
var app = angular.module("appUserSchedule", ['ui.bootstrap']);
app.controller("CtrlUserSchedule", function($scope,$http,$location,$modal) {
$scope.ctrl = this;
$http.get('userschedule.json').success(function(data, status, headers, config) {
$scope.userscheds = data.userschedules;
//console.log(data);
}).error(function(data, status, headers, config) {
console.log("No data found..");
});
// Show modal
this.showModal = function (index) {
var modalInstance;
modalInstance = $modal.open({
templateUrl: 'modalContent.html',
controller: 'CtrlUserSchedule',
scope: $scope
});
objts = new Date($scope.userscheds[index].datetime_start);
objte = new Date($scope.userscheds[index].datetime_end);
$scope.myst = objts;
$scope.myet = objte;
// Save User Schedule Entry details after making a change, then close modal
$scope.saveUserScheduleEntry = function() {
// Displays original value, but where are my updated values?
alert(JSON.stringify($scope.userscheds[index]));
$http.put('userschedule.json',index).success(function(eventsuccess){
}).error(function(err){
/* do something with errors */
});
modalInstance.close();
};
}
json
{
"userschedules":[
{
"id":1,
"week_day":"Monday",
"datetime_start":"2016-03-08T08:00:00-05:00",
"datetime_end":"2016-03-08T12:00:00-05:00",
"time_start":"08:00",
"time_end":"12:00"
},
{
"id":21,
"week_day":"Monday",
"datetime_start":"2016-03-08T13:00:00-05:00",
"datetime_end":"2016-03-08T17:00:00-05:00",
"time_start":"13:00",
"time_end":"17:00"
}, ...
I am trying to learn Angular JS with an HTML Sample. I would like the user to fill out some basic information, and based on the checkbox they select, it will load a form page using the UI Routing. It will generate links to navigate the page automatically, based on the checkboxes selected. Then, once the form is complete it should save in a directory on the server, and download to the user computer.
I got the form to show all data as json array, but now nothing is working after trying to add the ability to create the checklist links, as navigation, and saving?
App.js
create our angular app and inject ngAnimate and ui-router
angular.module('formApp', ['ngAnimate', 'ui.router'])
//configuring our routes
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('form', {
url: '/form',
templateUrl: 'form.html',
controller: 'formController'
})
// nested states
// each of these sections will have their own view
// url will be nested (/form/profile)
.state('form.profile', {
url: '/profile',
templateUrl: 'form-profile.html'
})
// url will be /form/interests
.state('form.interests', {
url: '/interests',
templateUrl: 'form-interests.html'
})
// url will be /form/payment
.state('form.payment', {
url: '/payment',
templateUrl: 'form-payment.html'
});
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/form/profile'); })
// our controller for the form //
.controller('formController', function ($scope) {
// we will store all of our form data in this object
$scope.prefContactArray = [];
$scope.prefContactArray.push({ name: "Text", reply: "Great we'll text you.", isDefault: false });
$scope.prefContactArray.push({ name: "Email", reply: "Great we'll send you an email!", isDefault: false });
$scope.prefContactArray.push({ name: "Phone", reply: "Great we'll give you a call.", isDefault: false });
$scope.selectedprefContact = $scope.prefContactArray.name;
$scope.selectedprefContactReply = $scope.prefContactArray.reply;
$scope.fruitsList = [
{ id: 1, name: 'Apple', url: 'form/profile.html', state:'.profile' },
{ id: 2, name: 'Banana', url: 'form/interests.html', state:'.interests' },
{ id: 3, name: 'Guava', url: 'form/payment.html', state:'payment' }
];
$scope.selected = {
fruitsList: []
};
$scope.checkAll = function () {
$scope.selected.fruitsList = angular.copy($scope.fruitsList);
};
$scope.uncheckAll = function () {
$scope.selected.fruitsList = [];
};
$scope.create = function () {
var aTag = document.createElement('a ui-sref-active="active" ui-sref="fruitsList.state"
alt="fruitsList.name"');
status-buttons.appendChild(aTag);
$state.go($scope.selected.fruitsList.url);
};
$scope.formData = {};
$scope.submit = function downloadFile(fileName, urlData) {
var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = fileName;
aLink.href = urlData;
aLink.dispatchEvent(evt);
}
var data = $scope.formData;
downloadFile('test.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data));
});
Form.html
<div id="form-container">
<div class="page-header text-center">
<h2>Let's Be Friends</h2>
<!-- the links to our nested states using relative paths -->
<!-- add the active class if the state matches our ui-sref -->
<div id="status-buttons" class="text-center">
<a ui-sref-active="active" ui-sref=".profile"><span>1</span> Profile</a>
<a ui-sref-active="active" ui-sref=".interests"><span>2</span> Interests</a>
<a ui-sref-active="active" ui-sref=".payment"><span>3</span> Payment</a>
</div>
</div>
<div id="splitscreen">
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="signup-form" ng-submit="createQuote()">
<div id="userPanel" class="col-md-6" style="background-color:#999; z-index:2;">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" ng-model="formData.name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" ng-model="formData.email">
</div>
<div class="form-group">
<label for="email">Phone</label>
<input type="text" class="form-control" name="email" ng-model="formData.phone">
</div>
<div class="form-group">
<label for="email">Website</label>
<input type="text" class="form-control" name="email" ng-model="formData.web">
</div>
<div ng-repeat="prefContact in prefContactArray">
<label>
<input type="radio" ng-value="prefContact.reply" ng-model="$parent.selectedprefContact" />
{{prefContact.name}}
</label>
</div>{{selectedprefContact | json}}
<div>
<label ng-repeat="fruit in fruitsList">
<input type="checkbox" checklist-model="selected.fruitsList" checklist-value="fruit.id"
ng-click="create()" /> {{fruit.name}}<br />
</label>
<button ng-click="checkAll()">Check all</button>
<button ng-click="uncheckAll()">Uncheck all</button> <br />
{{selected.fruitsList}}
</div>
</div>
</div>
<pre>
{{ formData }}
</pre>
<div id="questions" class="col-md-6">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</div> </form>
</div>
</div>
<!-- show our formData as it is being typed -->
Submit Button Page
Thanks For Your Money!
<button type="submit" class="btn btn-danger">Submit</button> </div>
Index
<!-- CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/darkly/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<!-- JS -->
<!-- load angular, nganimate, and ui-router -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app --> <body ng-app="formApp">
<div class="container col-md-12">
<!-- views will be injected here -->
<div class="col-md-12" ui-view></div>
</div>
In your create() function you use $state.go($scope.selected.fruitsList.url) which will change to the new state, however the value is the template path rather than the state path.
You should use $state.go($scope.selected.fruitsList.state) because the 'to' parameter of $state.go() should be the name of the state that will be transitioned to or a relative state path. If the path starts with ^ or . then it is relative, otherwise it is absolute.
$state
As #Andorov already mentioned, you need $state to navigate. UI Router has offers this service to make it easy for you to go from one state (or route, or page) to another. Add the dependency to your controller like so:
.controller('formController', function ($scope, $state) {
You are now able to say something like $state.go('form.payment') in your controller. This will navigate the person to the Payment form.
So all you would need to do now is when they submit the form (i.e. inside your $scope.createQuote() function which you haven't included in the code yet), find out what state you should go to and end with $state.go(stateToGoto).
Tip:
When I started out with UI router and AngularJs, I just made every route its own page, not using children. If you would do that you would get:
A route for your form
A route for every page it could go to.
Every route has its own controller, which makes it easy to put code in the right place. I don't like sharing the controller between children as it just makes it more difficult to understand which part of the code is for which child.
Does this help?
I have a controller (called "catalogueController") that manages my search box and my search page. I have the controller initially set the page to automatically call the search function defined in "catalogueController" when the app loads to pre-load my array of items (called Inventory) to be repeated via ng-repeat in the page.
The process runs like this:
1. I submit the search form.
2. "catalogueController" will send the search term to my factory (called "Search").
3. "Search" will have a function which will make a server call to query my database for that particular search.
4. The database will send the results of the search to the "Search" factory.
5. The "Search" factory will send the results to the "catalogueController" controller.
6. "catalogueController" will update the $scope.Inventory to be equal to the new result that I was received.
My problem is that ng-repeat does not refresh itself to display my new and updated $scope.Inventory array. $scope.Inventory definitely is updated (I have made sure of this through various console logs).
I have also tried to use $scope.$apply(). It did not work for me.
Thank you in advance for your help!
Here is my code:
HTML Template
<form role="search" class="navbar-form navbar-left" ng-controller="catalogueController" ng-submit="search(search_term)">
<div class="form-group">
<input type="text" placeholder="Search" class="form-control" ng-model="search_term">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
<main ng-view></main>
catalogue.html partial
<div id="main" class="margin-top-50 clearfix container">
<div ng-repeat="items in inventory" class="row-fluid">
<div class="col-sm-6 col-md-3">
<div class="thumbnail"><img src="image.jpg" alt="..." class="col-md-12">
<div class="caption">
<h3>{{ items.itemName }}</h3>
<p>{{ items.description }}</p>
<p>Buy <a href="#" role="button" class="btn btn-default">More Info</a></p>
</div>
</div>
</div>
</div>
"app.js" Angular App
var myApp = angular.module('qcbApp', ['ngRoute', 'ngCookies', 'appControllers']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'html/partials/login.html',
controller: 'registrationController'
}).
when('/sign-up', {
templateUrl: 'html/partials/sign-up.html',
controller: 'registrationController'
}).
when('/catalogue', {
templateUrl: 'html/partials/catalogue.html',
controller: 'catalogueController'
}).
when('/', {
templateUrl: 'html/partials/qcbhome.html'
}).
otherwise({
redirectTo: '/'
});
}]);
"catalogueController" Controller
myApp.controller('catalogueController', ['$scope', 'Search', function($scope, Search) {
var time = 0;
var searchCatalogue = function(search) {
$scope.inventory = null;
console.log("Controller -- "+search);
Search.searchCatalogue(search)
.then(function(results) {
console.log(results);
$scope.inventory = results;
});
};
if(time == 0)
{
searchCatalogue('');
time++;
}
$scope.search = function(term) {
searchCatalogue(term);
}
}]);
"Search" Factory
myApp.factory('Search', ['$http', '$q', function($http, $q) {
function searchCatalogue(term) {
var deferred = $q.defer();
console.log("Factory -- "+term);
$http.post('/catalogue_data', {term: term}, {headers: {'Content-Type': 'application/json'}})
.success(function(result) {
console.log(result[0].SKU);
deferred.resolve(result);
console.log("Factory results -- "+result);
});
return deferred.promise;
}
return {
searchCatalogue: searchCatalogue
}; //return
}]);
I think the problem is the ng-repeat can not access the inventory in scope. You have to create a div which contains both the form and the ng-repeat.
The html should be:
<div ng-controller="catalogueController">
<!-- Move the controller from the form to parent div -->
<form role="search" class="navbar-form navbar-left" ng-submit="search(search_term)">
<div class="form-group">
<input type="text" placeholder="Search" class="form-control" ng-model="search_term">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
<div id="main" class="margin-top-50 clearfix container">
<div ng-repeat="items in inventory" class="row-fluid">
<div class="col-sm-6 col-md-3">
<div class="thumbnail"><img src="image.jpg" alt="..." class="col-md-12">
<div class="caption">
<h3>{{ items.itemName }}</h3>
<p>{{ items.description }}</p>
<p>Buy <a href="#" role="button" class="btn btn-default">More Info</a></p>
</div>
</div>
</div>
</div>
</div>
I've seen the situation a few times where when you are updating a property directly on the $scope object there are interesting problems around databinding to that value (such as inventory). However if you databind to an object property of an object then the databinding works as expected. So for example use a property on $scope. I believe this is a copy by value vs copy by reference issue.
Update all your inventory references as follows
$scope.data.inventory = result;
Also don't forget to update your inventory reference in the html template:
<div ng-repeat="items in data.inventory" class="row-fluid">
Update: I made this plunk to figure it out - http://plnkr.co/edit/0ZLagR?p=preview
I think the primary problem is you have the controller specified twice. I removed it from the form and it started working.