I have this 2 parts of AngularJS codes in my Django powered webpage.
Part1
<div class="categoryList">
<ul>
<li data-ng-repeat="cat in categories">
<a>{$ cat.name $}</a>
</li>
</ul>
</div>
Part 2
<li data-ng-repeat="i in range(pictures[currentCat].length)">
<a data-ng-click="changePage(i)">{$ i $}</a>
</li>
This is my controller
$scope.currentPage = 1;
$scope.currentCat = 0;
$.getJSON('categories/',
function(data) {
$scope.categories= data;
});
$scope.pictures=[cat1,cat2,cat3,cat4,cat5]; //cat1..cat5 are some dictionaries like 'categories'
$scope.changePage = function(i){
$scope.currentPage=i;
};
The problem is part 2 works fine while loading the page, But part1 doesn't work until I click on a page number from part2 list and run 'changePage'
This was working fine when my webpage wasn't powered by Django
Update
views.py
def getcategories(request): // /categories/ url runs this
dictionaries = [obj.as_json() for obj in Category.objects.all()]
return HttpResponse(json.dumps(dictionaries), content_type='application/json')
models.py
class Category(models.Model):
name = models.CharField(default='other',max_length=50)
upload_date = models.DateTimeField(default=datetime.now, blank=True)
def as_json(self):
return {
"id": self.id,
"name": self.name
}
As simpe says the output should be {{cat.name}} and {{i}}.
About the "categories", check that the url is working, and then using your browser developer tools see that the right url is invoked.
Also you can use django rest framework and $resource to send your data between front-end and back-end.
I added $scope.$apply() to $.getJSON and now it updates $scope.categories as soon as it gets the results. and everything is working fine now.
$.getJSON('categories/',
function(data) {
$scope.categories= data;
$scope.$apply();
});
Related
I have an application I am building using an Angular JS front end and a REST-based API back end feeding a MySQL database. There are REST calls made from the front end to the back end to populate or retrieve data in the database. I want to add a drop down selection box to my angular JS front end home page. I want the selection to trigger a REST call to the database, to retrieve a specific value and have that value become a part of a dynamically loaded html partial.
As an example, the drop down would select a model of a car (Toyota Corolla, Honda Accord, etc.) When you select that model, the controller would make a REST call to the appropriate table(s) to get the rest of the information for that car (MPG, size, weight, etc.) Once it did this, it would load a partial HTML on the page that was a template HTML file but with dynamic content. So the page loaded would be /#/carInfo?toyotaCorolla. The template partial html file would load and then the tables on the template would populate with the response from that REST call. So I would essentially have a single template for that page, but it would call a new VERSION of the page based on what was selected.
I am thinking about this in my head and I do not have my application code with me. This question is not for the actual code solution, but for someone to either write up some pseudo code or point me to a demo/example online that is similar to this...if it is even possible. I am doing searches on my own, but I may be searching for the wrong terminology to get this accomplished. Any pointers or help on this would be appreciated.
UPDATE:
Now that I am home, here is a snippet of the code I am having issues with.
<ul class="nav navbar-nav">
<li></li>
<li class="dropdown">
<a href="javascript:void(0)" data-target="#" class="dropdown-toggle" data-toggle="dropdown">
Select a car...
<b class="caret"></b></a>
<ul class="dropdown-menu">
<li ng-model="selectedCar.value" ng-repeat="x.car for x in cars"
ng-change="selectedCarChanged()"></li>
</ul>
</li>
</ul>
That is not populating correctly. I have the same ng code for a <select> implementation using ng-options instead of ng-repeat. I was hoping it would be a simple transition, but the CSS version using the lists is not working.
Please find the code snippet below. Hope this will be helpful
car-list.html
<div ng-controller="carListController">
<select ng-model="selectedCar" ng-change="onSelectCar(selectedCar)">
<option ng-repeat="car in cars">{{car}}</option>
</select>
</div>
carListController.js
app.controller('carListController', function($scope, $location) {
$scope.carList = ['Honda', 'Toyota', 'Suzuki', 'Hyundai'];
$scope.onSelectCar = function(car) {
$location.path('#/carInfo').search({carInfo: car});
}
});
carInfo.html
<div class="carDetails">
<span>Car Name: {{car.name}}</span>
<span>Car Model: {{car.model}}</span>
<span>Car Year: {{car.year}}</span>
<span>Car Size: {{car.size}}</span>
</div>
carInfoDetailsController.js
app.controller('carInfoController', function($scope, $location, $http) {
$scope.car = {};
$scope.init= function() {
$http.get('url/' + $location.search('carInfo'), function(response) {
$scope.car = response;
});
};
$scope.init();
});
appConfig.js
app.config(function($routeProvider){
$routeProvider.when('/carInfo'{
templateUrl: "carInfo.html",
controller: "carInfoController"
});
});
something like:
//in a service
(function() {
function MyService($http) {
var myService = {};
MyService.accessMultiTool = function(){
var args = Array.from(arguments);
var method, url, authorization;
args.forEach(function(item){
if('method' in item){
method = item.method;
}else if ('url' in item){
url = item.url;
}else if ('authorization' in item){
authorization = item.authorization;
}
});
delete $http.defaults.headers.common['X-Requested-With'];
return $http({
method: method,
origin: 'http://someclient/',
url: url,
headers: {'Authorization': authorization}
}).error(function(status){generate some error msg});
};
return MyService;
}
angular
.module('myApp')
.factory('MyService', ['$http', MyService]);
})();
//in a controller
(function () {
function MyCtrl(MyService) {
var myController = this;
this.car_model_options = ["Honda", "Chevy", "Ford", "Nissan"];
this.bound_car_model_obj = {
model: null
};
this.getCarModel = function(){
MyService.accessMultiTool({method: 'GET'}, {url: 'http://somebackend/api/cars/' + myController.bound_car_model_obj.model}, {authorization: this.activeMember.auth}).then(function(data){
myController.setCurrCarModel(data);
});
this.setCurrCarModel = function(data){
myController.currently_selected_car_model = data;
};
};
};
angular
.module('myApp')
.controller('MyCtrl', ['MyService', MyCtrl]);
})();
//in a template
<div ng-controller="MyCtrl as mycontroller">
<select data-ng-init="this.bound_car_model_obj.model = mycontroller.car_model_options[0]" data-ng-model="this.bound_car_model_obj.model" data-ng-options="option for option in mycontroller.car_model_options" >
</select>
<table>
<tr ng-repeat="car in mycontroller.currently_selected_car_model>
<td>{{car.someproperty}}>/td>
<td>{{car.someotherproperty}}>/td>
</tr>
</table>
</div>
I am working on a web app where non-profit organizations can create a profile and be easily searchable by various parameters. In the "create and organization" form, I have a nested array where the organization can add donations that they need. The array is storing ok (I can add multiple donations), however when I try to display it using ng-repeat, nothing renders. When I don't use the ng-repeat and just display via {{ ctrl.organization.donations }} the information shows up with brackets and quotation marks.
Here is the code that I use to add the donations (via the newOrganization controller):
function NewOrganizationController(OrganizationService, CategoryService, $stateParams, $state, $http, Auth){
var ctrl = this;
CategoryService.getCategories().then(function(resp) {
ctrl.categories = resp.data;
});
ctrl.donations = [{text: ''}];
Auth.currentUser().then(function(user) {
ctrl.user = user;
})
ctrl.addNewDonation = function() {
var newDonation = ctrl.donations.length+1;
ctrl.donations.push({text: ''});
};
ctrl.removeDonation = function() {
var lastItem = ctrl.donations.length-1;
ctrl.donations.splice(lastItem);
};
ctrl.addOrganization = function() {
var donations = this.donations;
var allDonations = [];
for (var key in donations) {
if (donations.hasOwnProperty(key)) {
var donation = donations[key].text;
allDonations.push(donation);
}
}
var data = {
name: ctrl.organization.name,
description: ctrl.organization.description,
address: ctrl.organization.address,
donations: allDonations.join("/r/n"),
category_id: this.category.id
};
OrganizationService.createOrganization(data);
$state.go('home.organizations');
};
}
angular
.module('app')
.controller('NewOrganizationController', NewOrganizationController);
Here is the code that I am using to display the array on my show page (this is what shows up with brackets, i.e. donations needed: ["food", "clothing"]):
<h5>{{ ctrl.organization.donations }}</h5>
This is the ng-repeat code that is not rendering anything to the page:
<li class="list-group-item" ng-repeat="donation in donations track by $index">
{{ donation }}
</li>
I've tried to use .join(', ') within the {{donation}} brackets, but this isn't recognized as a function.
edit: After taking AJ's suggestion here is a screenshot of what appears...anyone know how to fix this?
seems that my array is showing up in table form, with each row containing one character
Any help would be greatly appreciated. Here is a link to the github repo in case you want to look at anything else or get a bigger picture.
You need to use the same variable name that works in the h5
<li class="list-group-item" ng-repeat="donation in ctrl.organization.donations track by $index">
{{ donation }}
</li>
I have created a basic tool using vanilla javascript/html/css to perform certain functions across all emails associated with the business. To maintain the code base simplicity, i have started to porting the application using angularJS, creating modules/controllers etc. However, i got stuck with below situation. It looks like from the logs that my included html template gets called before data is ready from the controller.
I am placing an ajax call from the server which roughly takes ~1 sec. But by the time, I guess Angular executes the included template and because of no model availability, it renders nothing on the application side.
A look into my code:
index.html
<div class="tab-pane active fade in" id="results">
<section ng-controller = "messageSelectionController" ng-include src="'templates/messageSelectionTemplate.html'"></section>
</div>
messageSelectionController.js
app.controller('messageSelectionController',function($scope,$log){
//Generic ajax call
var makeRequest = function(paramObj,successCallback,errorCallBack,url,type){
$.ajax({
method : type ? type : "GET",
url : url ? url : "https://xx.xx.xx/xx/xx",
data : paramObj,
xhrFields : { withCredentials : true }
}).then(successCallback,errorCallBack);
};
var messageSelectionSuccessHandler = function(data){
$scope.messageselectionlist = JSON.parse(data).response.docs;
$log.info($scope.messageselectionlist);
};
var messageSelectionErrorHandler = function(data){
$log.info(data.responseText);
};
var data = {
q : "",
fq:[
'View:xx',
'Platform:xx'
],
start : 0,
rows : 9999
};
makeRequest(data, messageSelectionSuccessHandler,messageSelectionErrorHandler);
});
messageSelectionTemplate.html
<ul>
<li ng-repeat="item in messageselectionlist">
<article class="">
<span class="label label-success">MessageSelection</span>
<a> "Platform : {{item.Platform}} | View : {{item.View}} | Locale : {{item.Locales[0]}}"
<i class = "ocon-flag-{{item.Locales[0] | lowercase }}"></i>
</a>
<span class = "label label-inverse">{{item.Description}}</span>
</article>
</li>
</ul>
I tried to put logs to see when the messageSelectionTemplate is loaded, using below code:
$scope.$on('$includeContentLoaded', function(event, target){
console.log(event); //this $includeContentLoaded event object
console.log(target); //path to the included resource, 'snippet.html' in this case
});
and here's the logs:
-----templates/messageSelectionTemplate.html angular.js:13424
-----Array[654]
Can someone let me know how to defer the included template loading until the modal for template is not available. Thanks!
I have a Play framework project using AngularJS for its views. The controller responsible for querying data makes 2 requests, each returning a JSON block. The first one works correctly and it's displayed properly. The second one's data is pretty much destroyed by Angular (example below).
The JSONs are created correctly prior to being rendered, as it's shown through the application's log.
This is the correct JSON (taken from the Play Framework routed method's log):
{"id":5,"name":"auditoria","url":null,"version":1,"methods":[]}
This is how AngularJS prints it. It tokenizes :
[{},{"0":"a","1":"u","2":"d","3":"i","4":"t","5":"o","6":"r","7":"i","8":"a"},{},{},{"length":0}]
And here's the controller:
app.controller("ViewCtrl", [ "$scope", "$resource", "$routeParams", "apiUrl",
function($scope, $resource, $routeParams, apiUrl) {
var ServiceList = $resource(apiUrl + "/services");
$scope.services = ServiceList.query(); //JSON is displayed properly
if ($routeParams.id) {
jsonServicoQuery = apiUrl + "/services/" + $routeParams.id
var Service = $resource(jsonServicoQuery);
$scope.currentService = Service.query(); //JSON is butchered
}
} ]);
Here's the HTML:
<div class="row">
<div class="col-md-3">
<div class="bs-sidebar hidden-print" role="complementary">
<ul class="nav bs-sidenav">
<li><i class="fa fa-plus"></i></li>
<li ng-repeat="s in services| orderBy:'name'">{{s.nome}}
<ul>
<li ng-repeat="m in s.methods| orderBy:'name'">{{m.name}}
[{{m.id}}]</li>
</ul></li>
</ul>
</div>
</div>
<div class="col-md-9" role="main">
<div class="bs-docs-section">
<div class="page-header">
<!-- displaying the whole currentService JSON for debugging purposes -->
{{currentService}}
</div>
</div>
</div>
</div>
Anybody has any clues about what am I doing wrong?
Update: Service.query() executes the method routed by Play Framework.
Route configuration:
GET /api/services/:id controllers.Services.show(id: String)
And controllers.Services.show(id: String) implementation:
public static Result show(String id) {
Service s = Service.findById(id);
//JSON displayed here is correct, log below
Logger.info("At Services show, json " + Json.toJson(s));
return ok(Json.toJson(s));
}
Log:
[info] application - At Services show, json {"id":5,"name":"auditoria","url":null,"version":1,"methods":[]}
I managed to find the problem, I should have used $scope.currentService = Service.get(); instead of $scope.currentService = Service.query();
I'm following John Papa's jumpstart course about SPA's and trying to display a list of customers loaded via ASP.NET Web API the knockout foreach binding is not working. The Web API is working fine, I've tested it on it's own and it is returning the correct JSON, because of that I won't post the code for it. The get method simply returns one array of objects, each with properties Name and Email. Although not a good practice, knockout is exposed globaly as ko by loading it before durandal.
I've coded the customers.js view model as follows
define(['services/dataservice'], function(ds) {
var initialized = false;
var customers = ko.observableArray();
var refresh = function() {
return dataservice.getCustomers(customers);
};
var activate = function() {
if (initialized) return;
initialized = true;
return refresh();
};
var customersVM = {
customers: customers,
activate: activate,
refresh: refresh
};
return customersVM;
});
The dataservice module I've coded as follows (I've not wrote bellow the function queryFailed because I know it's not being used)
define(['../model'], function (model) {
var getCustomers = function (customersObservable) {
customersObservable([]);
var options = {url: '/api/customers', type: 'GET', dataType: 'json'};
return $.ajax(options).then(querySucceeded).fail(queryFailed);
function querySucceeded(data) {
var customers = [];
data.forEach(function (item) {
var c = new model.Customer(item);
customers.push(c);
});
customersObservable(customers);
}
};
return {
getCustomers: getCustomers
};
});
Finaly the model module was built as follows:
define(function () {
var Customer = function (dto) {
return mapToObservable(dto);
};
var model = {
Customer: Customer
};
return model;
function mapToObservable(dto) {
var mapped = {};
for (prop in dto)
{
if (dto.hasOwnProperty(prop))
{
mapped[prop] = ko.observable(dto[prop]);
}
}
return mapped;
}
});
The view is then simply a list, it is simply:
<ul data-bind="foreach: customers">
<li data-bind="text: Name"></li>
</ul>
But this doesn't work. Any other binding works, and I've looked on the console window, and it seems the observable array is being filled correctly. The only problem is that this piece of code doesn't show anything on screen. I've reviewed many times the files but I can't seem to find the problem. What's wrong with this?
You can use the knockout.js context debugger chrome extension to help you debug your issue
https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof
Well, I just spent a lot of time on an local issue to realize that the ko HTML comment format, if used, should be like this:
<!-- ko foreach: arrecadacoes -->
and NOT like this:
<!-- ko: foreach: arrecadacoes -->
: is NOT used after ko...
I know this question is a little old but I thought I'd add my response in case someone else runs into the same issue I did.
I was using Knockout JS version 2.1.0 and it seems the only way I can get the data to display in a foreach loop was to use:
$data.property
so in the case of your example it would be
$data.Name
Hope this helps
I don't see anywhere in your code that you've called ko.applyBindings on your ViewModel.
KO has a known issue while using foreach in a non-container element like the one above <ul> so you have to use containerless control flow syntax.
e.g.
<ul>
<!-- ko foreach: customers-->
<li data-bind="text: Name"></li>
<!-- /ko -->
</ul>
Ref: http://knockoutjs.com/documentation/foreach-binding.html