I have form created in symfony2, which at the end renders button to submit form. When I add ng-app="myApp" everything works fine, but I can't submit form which is on this page. Why is that and how to unblock this?
FORM:
->add('company','choice',array(
'mapped' => false,
'attr'=>array('ui-select2'=>'myArray', 'ng-model'=>'form.company','ng-options'=>'option.value as entity.name_company for entity in entities','ng-change' => 'changeItem()')
))
->add('project',null,array(
'attr'=>array('ui-select2'=>'myArray2', 'ng-model'=>'form.task','ng-options'=>'option.value as entity.description_task for entity in tasks')
))
VIEW:
<html ng-app="flowApp">
<head>
<link rel="stylesheet" href="{{ asset('external-libs/select2/select2.css')}}">
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="{{ asset('external-libs/select2/select2.js')}}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js"></script>
<script src="{{ asset('external-libs/select2.js')}}"></script>
<script src="{{ asset('external-libs/app.js') }}"></script>
<style>
.select2-choice { width: 220px; }
</style>
</head>
<body>
<div class="container" ng-controller="MainCtrl">
{{ form(form) }}
</div>
</body>
</html>
SCRIPT:
var app = angular.module('flowApp', ['ui.select2']).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}
);
app.controller('MainCtrl', function ($scope, $element,$http) {
$http({method: 'GET', url: 'companies.json'}).
success(function(data, status, headers, config) {
$scope.entities = data.entities;
$scope.form = {company: $scope.entities[0].value };
console.debug(data.entities);
});
});
Well documentation says:
For this reason, Angular prevents the default action (form submission
to the server) unless the element has an action attribute
specified
so you can add action attribute to your form. In my example i am using grenerateUrl function, but you should generate url of your current route(route of controller where the form is generated)
$data = array();
$form = $this->createFormBuilder($data,
array("action" => $this->generateUrl("route_to_curent_path"))))
->add('field', 'text')
->add('submitButton', 'submit')
->getForm();
EDIT:
just now found out that this is a duplicate question here and here and here
and here(this link being the most upvoted answer)
We need more informations, did you let browser validate form ? To remove :
{{ form(form, {
'attr': {
novalidate,
},
})
}}
Maybe errors popup are hidden (happen with various complexe form fields)
When you said "i can't submit", is the submit button unable ? Errors happen after sumbission ?
Related
I'm trying to make a foreign language chat app (because I love languages) that is similar to Omegle.com!
I'm making my chat application using PubNub and AngularJS.
Basically, my chat app is designed like this:
First the user is presented with a screen of what language they can speak and what language they want to learn
Let's say I am an English speaker and I am learning German (HomeController)
They press the CHAT! button and goes to my ChatController
From here, the user is in a queue until a native speaker match to their learning language is found (this is the part where I'm having the most trouble)
Here are pictures to get a better idea: http://imgur.com/a/1yGST
Here is what I have so far:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Linga!</title>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="css/reset.css" />
<link rel="stylesheet" type="text/css" href="css/semantic.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- AngularJS and jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<!-- PubNub Service -->
<script src="http://cdn.pubnub.com/pubnub.min.js"></script>
<script src="https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-4.0.2.min.js"></script>
<!-- Underscore support -->
<script src="js/vendor/underscore-min.js"></script>
<!-- Scroll Glue -->
<script src="https://cdn.rawgit.com/Luegg/angularjs-scroll-glue/master/src/scrollglue.js"></script>
<!-- Semantic UI JS -->
<script src="js/vendor/semantic.min.js"></script>
</head>
<body ng-app="ChatApp">
<div ng-view></div>
<!-- App -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/HomeController.js"></script>
<script src="js/controllers/ChatController.js"></script>
</body>
</html>
I'm using ng-view to route between my HomeController.js and ChatController.js.
home.html View
<div id="background"></div>
<div class="main">
<div class="ui container">
<div class="ui center aligned segment glass">
<h1 id="linga">Ling<span>a</span></h1>
<form class="ui form" ng-submit="submit()" name="chatForm">
<div class="field">
<label>I speak</label>
<select class="ui fluid dropdown" ng-model="selectedNative" ng-options="language.name for language in languages">
<option value="">Language</option>
</select>
</div>
<div class="field">
<label>Find someone</label>
<select class="ui fluid dropdown" ng-model="selectedLearning" ng-options="language.name for language in languages">
<option value="">Language</option>
</select>
</div>
<button class="ui button" id="submit" type="submit">CHAT</button>
</form>
</div>
</div>
</div>
Here the user selects what language they are native in and what they are learning. And then the chat button is pressed which goes to the submit() function in my HomeController.js.
HomeController.js
app.controller('HomeController', ['$scope', '$location', 'languageService', function($scope, $location, languageService){
//$scope.hello = "hi!";
$scope.languages = [
{
name:'German',
flag:'img/flags/de.png'
},
{
name:'French',
flag:'img/flags/fr.png'
},
{
name:'English',
flag:'img/flags/us.png'
},
{
name:'Portuguese',
flag:'img/flags/br.png'
},
{
name:'Persian',
flag:'img/flags/ir.png'
},
{
name:'Russian',
flag:'img/flags/ru.png'
},
{
name:'Swedish',
flag:'img/flags/se.png'
},
{
name:'Turkish',
flag:'img/flags/tr.png'
},
{
name:'Spanish',
flag:'img/flags/es.png'
},
{
name:'Italian',
flag:'img/flags/it.png'
}
];
$scope.submit = function(){
languageService.setNative($scope.selectedNative.name);
languageService.setLearning($scope.selectedLearning.name);
$location.path("/chat");
}
}]);
$(document).ready(function(){
$('.ui.dropdown').dropdown();
});
Here the submit() function in my HomeController.js puts the native and learning language information in my languageService so that my ChatController.js can use the information.
app.js
var app = angular.module('ChatApp', ['ngRoute', 'pubnub.angular.service', 'luegg.directives']);
app.service('languageService', function(){
var languages = {
nativeLanguage: '',
learningLanguage: ''
};
return{
setNative: setNative,
setLearning: setLearning,
getLanguages: getLanguages
};
function getLanguages(){
return languages;
};
function setNative(nativeLanguage){
languages.nativeLanguage = nativeLanguage;
};
function setLearning(learningLanguage){
languages.learningLanguage = learningLanguage;
};
});
app.config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
controller:'HomeController',
templateUrl:'views/home.html'
})
.when('/chat', {
controller:'ChatController',
templateUrl:'views/chat.html'
})
.otherwise({
redirectTo: '/'
});
});
app.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
This service in app.js puts the information attained from HomeController.js and makes them available for controllers.
ChatController.js
app.controller('ChatController', ['$scope', '$rootScope', 'languageService', 'Pubnub',
function($scope, $rootScope, languageService, Pubnub){
$scope.languages = languageService.getLanguages();
$scope.channel = 'messages-channel';
// Generating a random uuid between 1 and 100 using an utility function from the lodash library.
$scope.uuid = _.random(100).toString();
Pubnub.init({
publish_key: 'demo',
subscribe_key: 'demo',
uuid: $scope.uuid
});
// Send the messages over PubNub Network
$scope.sendMessage = function() {
// Don't send an empty message
if (!$scope.messageContent || $scope.messageContent === '') {
return;
}
Pubnub.publish({
message: {
content: $scope.messageContent,
sender_uuid: $scope.uuid,
date: new Date()
},
channel: $scope.channel
});
// Reset the messageContent input
$scope.messageContent = '';
}
$scope.messages = [];
// Subscribing to the ‘messages-channel’ and trigering the message callback
Pubnub.subscribe({
channel: $scope.channel,
withPresence: true,
triggerEvents: ['callback']
});
// Listening to the callbacks
$rootScope.$on(Pubnub.getMessageEventNameFor($scope.channel), function(ngEvent, m){
$scope.$apply(function(){
$scope.messages.push(m);
});
});
}]);
chat.html View
<div class="main-chat">
<div class="ui container">
<div class="chat-box ui segment" id="style-3" scroll-glue>
<p>Searching for a {{languages.learningLanguage}} speaker ...</p>
<ul>
<li ng-repeat="message in messages">
<strong>Anonymous {{message.sender_uuid}}: </strong>
<span>{{message.content}}</span>
</li>
</ul>
</div>
<div class="chat-field ui segement">
<div class="ui form">
<textarea ng-enter="sendMessage()" ng-model="messageContent"></textarea>
</div>
</div>
</div>
</div>
And so here's where I'm stuck. For example, if I'm learning German, I want my chat app to stay in queue until a German native is found using the variables I made in my languageService. When it is found, they go into the chat and start learning languages!
My logic:
Need to find out who's currently using my app (for example 1,000 people)
Then I search in some sort of array for a native speaker I want to learn with
The most immediate match will terminate the loop (or listener) and go straight into chat
I did try adding Pubnub.addListener to my ChatController.js but it says that Pubnub.addListener is not a function error.
Tackled this problem for many hours reading a lot of tutorials on PubNub, but I can't figure it out at all.
Thank you so much for your help. I tried to make it as clear as possible.
First, addListener not a function must mean that PubNub object is out of scope (it must be) but don't have further insight at this time.
For your list of available native speakers, just create a channel for each language: native.german, native.french, etc. As users logon, have them subscribe to the proper native.<lang> channel.
You can use hereNow to get the list of active/online native speakers for that language.
And use PubNub Functions to do the translation in realtime without hitting your server to do that work.
I am using nodejs for the backend and angular for the fronend (and using materialize for css) and trying to write code for the signup. When I remove ng-model I get no errors, however, when I include ng-model in the input, the moment I start typing in the password/email field, I get a weird angular error : TypeError: n.is is not a function or TypeError: n.trigger is not a function . I have no idea what -n- is and dont have n function anywhere. Have been searching the internet etc. but cant figure out whats wrong.Also, signup does not work (it did before). Anyone has an idea? Thank you!
browser/js/signup.html
<div class="signup-wrapper">
<form id="signup-form" name="signupForm" ng-submit="signupForm.$valid && sendSignup(signup)">
<alert type="danger" ng-show="error"> {{ error }} </alert>
<div class="form-group">
<label for="email" >Email address</label>
<input style="width:300px;" type="text" ng-model="signup.email" class="form-control" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="signup-password">Password</label>
<input style="width:300px;" type="password" ng-model="signup.password" class="form-control" id="signup-password" placeholder="Password">
<input type="password" ng-model="signup.confirm" placeholder="Confirm Password">
</div>
<div class="signup-btn-group">
<button type="submit" class="btn btn-default">Sign Up</button>
</div>
</form>
</div>
browser/js/signup.js:
app.config(function ($stateProvider) {
$stateProvider.state('signup', {
url: '/signup',
templateUrl: 'js/signup/signup.html',
controller: 'SignupController'
});
});
app.controller('SignupController', function ($scope, AuthFactory, $state) {
$scope.signup = {};
$scope.sendSignup = function (signupInfo) {
AuthFactory.signup(signupInfo)
.then(function (response) {
if (response === 'email exists already') {
Materialize.toast('User already exists', 2000);
}
else if (response === 'not a valid email'){
Materialize.toast('It is not a valid email', 2000);
}
else if (response === 'passwords do not match'){
Materialize.toast('Your passwords do not match. Please try again!', 2000);
}
else {
Materialize.toast('Go ahead and login', 4000);
$state.go('login');
}
})
}
});
server/app/configure/authentication/local.js:
app.post('/signup', function(req, res, next) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var test = re.test(req.body.email);
if (req.body.password !== req.body.confirm) {
res.send('passwords do not match')
} else if (!test) {
res.send('not a valid email')
} else {
User.findOne({
where: {
email: req.body.email
}
}).then(function(userOrNull) {
if (userOrNull) {
res.send('email exists already')
} else {
User.create(req.body)
.then(function(user) {
req.login(user, function(err) {
if (err) console.log(err);
res.redirect('/login');
})
})
}
})
}
});
EDIT:
<link rel="stylesheet" type="text/css" href="/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="/materialize-css/bin/materialize.css">
<link rel="stylesheet" type="text/css" href="/style.css" />
<script src="/lodash/index.js"></script>
<script src="/angular/angular.js"></script>
<script src="/angular-animate/angular-animate.js"></script>
<script src="/angular-ui-router/release/angular-ui-router.js"></script>
<script src="/angular-ui-bootstrap/ui-bootstrap.js"></script>
<script src="/angular-ui-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="/socket.io-client/socket.io.js"></script>
<script type="text/javascript" src="/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/materialize-css/bin/materialize.js"></script>
<script type="text/javascript" src="/angular-materialize/src/angular-materialize.min.js"></script>
<script src="/main.js"></script>
You simply need to load your jQuery even before you load Angular.
This ensures that Angular can use the full jQuery library instead of jQlite.
Well had same issue with slick.min.js and angular-slick.min.js and after killing lots of time searching for solution finally I figured it out that issue was simple and my commonsense was not working.
I added the js files in following order and the error was gone. Hope someone finds it useful:
1) jquery.min.js
2) jquery-ui.min.js
3) slick.min.js
4) angular.js
5) angular-filter.js
6) angular-slick.min.js
...
...
In your case can try the following order and see if it works
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/materialize-css/bin/materialize.js"></script>
<script src="/angular/angular.js"></script>
<script src="/angular-animate/angular-animate.js"></script>
<script src="/angular-ui-router/release/angular-ui-router.js"></script>
<script src="/angular-materialize/src/angular-materialize.min.js"></script>
<script src="/angular-ui-bootstrap/ui-bootstrap.js"></script>
<script src="/angular-ui-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="/lodash/index.js"></script>
<script src="/socket.io-client/socket.io.js"></script>
<script src="/main.js"></script>
Your check to see if the form is $valid should be happening in your .js file. So on success, $scope.signupForm.$valid = true; and you would just have the sendSignup method call.
Also your sign up form is looking for some $scope.signup.confirm = true.. Which is why it could not be working (I dont see you actually using that).
Hope this helps! Let me know if you need more assistance.
You added more of the error message in a comment:
angular.js:14110 TypeError: n.trigger is not a function
at angular-materialize.min.js:1
at angular.js:19861
at completeOutstandingRequest (angular.js:6035)
at angular.js:6314
So, although you didn't mention it in the question, you are using the angular-materialize module and it is that module which is throwing the error. Looking at the uncompressed sources for angular-materialize I can see that it is expecting to find a trigger method on DOM elements.
The readme file for that module says:
Angular looks for jQuery and if no exists, it uses jQlite. Some
directives of angular-materialize uses some jQuery methods, so be sure
that Angular uses it instead of jQlite.
I think your problem is simply that you've used a module which depends on jQuery but you haven't included jQuery in your app.
I am using simple drag and drop effect based on the simple image upload example provided with the download of ng-flow. the drag-and-drop is working fine, but I want to stop the default upload action since I want to upload the image using the form submit action or using Angular .post() function:
<html ng-app="app" ng-controller="imageController" flow-init
flow-file-added="!!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]"
flow-files-submitted="$flow.upload()">
<head>
<title>Image</title>
<!-- <script src="../../bower_components/angular/angular.js"></script> -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="../../js/ng-flow-standalone.js"></script>
<script src="app.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css"
rel="stylesheet"/>
<style>
.thumbnail {
max-width: 200px; max-height: 150px; line-height: 20px; margin-bottom: 5px;
}
</style>
</head>
<body flow-prevent-drop>
<div class="container" >
<h1>flow image example</h1>
<hr class="soften"/>
<div>
<div class="thumbnail" ng-hide="$flow.files.length"
flow-drop flow-drag-enter="style={border:'4px solid green'}" flow-drag-leave="style={}" ng-style="style">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" />
</div>
<div class="thumbnail" ng-show="$flow.files.length">
<img flow-img="$flow.files[0]" />
</div>
<div>
Select image
Change
<a href="#" class="btn btn-danger" ng-show="$flow.files.length"
ng-click="$flow.cancel()">
Remove
</a>
</div>
<p>
Only PNG,GIF,JPG files allowed.
</p>
</div>
</div>
</body>
</html>
I tried to use event.preventDefault(); in "fileAdded" and "filesSubmitted" events handlers, but this is not stopping the upload start event. I want to execute the upload process during the form submit process.
When I use "return false" in "fileAdded" event, the image won't be inserted at all.
However, if I inject an error in the "filesSubmitted" event handler, the script will fail, and the upload won't be triggered. But this is not a clean way for achieving this effect.
I also used this code but it is preventing the image from being added to the page:
app.controller('imageController',
['$scope',
function ($scope) {
$scope.$on('flow::fileAdded', function (event, $flow, flowFile) {
console.log('$scope.$on', event, $flow);
event.preventDefault();//prevent file from uploading
console.log("event.preventDefault() executed.")
});
}])
See snapshots below for more details.
Appreciate your help to resolve this issue.
I figured out what is needed to stop triggering the upload action so that we can submit the image data during Angular post() instead of form submit action.
Either remove the configuration property target from:
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'upload.php',
permanentErrors: [404, 500, 501],
maxChunkRetries: 1,
chunkRetryInterval: 5000,
simultaneousUploads: 4,
singleFile: true,
};
or invoke the .pause() method from one of the events:
$scope.$on('flow::fileAdded', function (event, $flow, flowFile) {
console.log('flow::fileAdded - appraiser signature', event, $flow, flowFile);
...
$scope.processFile(flowFile);
flowFile.pause();
...
});
Or form this event inside the .config() function:
flowFactoryProvider.on('fileAdded', function(file, event){
console.log('fileAdded', file, event);
file.pause();
event.preventDefault();
console.log('file upload was paused.');
return true;
});
And, in order to retrieve the Base64 string of the selected image, you need to define the following function inside the controller:
$scope.processFile = function(flowFile){
console.log('$scope.processFile', flowFile);
var fileReader = new FileReader();
fileReader.onload = function (event) {
console.log('fileReader.onload - event=', event);
var uri = event.target.result;
$scope.imageString = uri;
$scope.imageStringB64 = uri.replace(/^data:image\/(png|jpg);base64,/, '');
};
fileReader.readAsDataURL(flowFile.file);
};
With the above, you have retrieved the Base64 value of the image in the scope variable imageStringB64 which you can then send to the server using $http.post() function instead of using the traditional form submit button.
I hope you will find the above useful.
Tarek
I'm trying to add the wysiwyg nicEdit text editor to my text areas. When I goto the actual templateUrl the textbox and tool bar do work but they do not submit correctly (to my firebase db). When I goto the page that is to render the template I am unable to get get nicEdit toolbar features and just get a regular text area box. I'm using angularjs and have the templateurl as addPost.html.
So again the template does render when I goto #/addPost but not with the working nicEdit features, yet going directly to the template url addPost.html does have the nicEdit features working but then won't submit to my firebase db. Anyone have an idea on why this is so? Thanks.
Template file addPost.html:
<head>
<script type="text/javascript" language="javascript" src="../nicEdit.js"></script>
<script type="text/javascript" language="javascript">
bkLib.onDomLoaded(nicEditors.allTextAreas);
</script>
<!-- Bootstrap core CSS -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<nav class="blog-nav">
<a class="blog-nav-item " href="#/welcome">Home</a>
<a class="blog-nav-item active" href="#/addPost">Add Post</a>
<a class="blog-nav-item " style="cursor:pointer;" ng-click="logout();">Logout</a>
</nav>
</head>
<body ng-controller="AddPostCtrl">
<div class="container" >
<form class="form-horizontal" ng-submit="AddPost()">
<fieldset>
<!-- Form Name -->
<legend>Create Post</legend>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="txtPost">Post</label>
<div class="col-md-4">
<textarea class="form-control" id="txtPost" ng-model="article.post" name="txtPost" ></textarea>
</div>
</div>
</fieldset>
</form>
</div><!-- /.container -->
</body>
addPost.js
'use strict';
angular.module('myApp.addPost', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/addPost', {
templateUrl: 'addPost/addPost.html',
controller: 'AddPostCtrl'
});
}])
.controller('AddPostCtrl', ['$scope','$firebase','$location','CommonProp',function($scope,$firebase, $location,CommonProp) {
if(!CommonProp.getUser()){
$location.path('/main');
}
$scope.logout = function(){
CommonProp.logoutUser();
}
$scope.AddPost = function(){
var title = $scope.article.title;
var date = $scope.article.date;
var post = $scope.article.post;
var firebaseObj = new Firebase("http://..");
var fb = $firebase(firebaseObj);
fb.$push({ title: title, date: date, post: post,emailId: CommonProp.getUser() }).then(function(ref) {
console.log(ref);
$location.path('/welcome');
}, function(error) {
console.log("Error:", error);
});
}
}]);
Going to #addPost shows the template with out nicEdit working
But going to the actual templateUrl addPost.html it works fine, minus not being able to submit
The problem has to do with trying to run scripts Angular html partials. The simple solution is to move the scripts you need to the head of your main index file, outside of ng-view, though it does seem (according to other stackoverflow posts) technically possibly to try to get these scripts to execute:
"AngularJS: How to make angular load script inside ng-include?"
https://stackoverflow.com/a/19715343/1078450
(Also, you have html in your head file that is not likely to be rendered: <nav class="blog-nav">)
Well, I have had the same problem, with initialisation of NicEdit in templates.
First I used onDomLoaded() else, but it's better to wait for the document. With jQuery I use document.ready.
Take a look here, pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The problem is to tell NicEditor the new textarea.
Here a code sample to do this in jQuery.
var idnr = 0;
var NicEditor = new nicEditor();
$('#add').click(function(){
var $clone = $('#dummy').clone();
var id = 't_' + idnr;
idnr = idnr + 1;
$clone.attr('id',id).attr('name',id).removeClass('dummy');
$('#wrapper').append($clone);
NicEditor.panelInstance(id);
$(nicEditors.findEditor(id).elm).focus();
});
And here is a working Example of dynamic NicEdit use.
I have a REST Service written in Java which returns an array of data in JSON like this:
[{"key":"London","value":"51.30"}]
Now I'm trying code an AngularJS REST clients using the AJS documentation. So far I've been able to invoke the REST service (I can see from the server logs) yet nothing is printed in the HTML page.
Here is my code:
<!doctype html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
<script language="javascript">
angular.module('myApp',['ngResource']);
function Ctrl($scope,$resource) {
var Geonames = $resource(
'http://localhost:8080/rest-application/rest/json', {
}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
}
);
$scope.objs = Geonames.query();
};
Ctrl.$inject = ['$scope','$resource'];
</script>
</head>
<body >
<div ng-app="myApp">
<div ng-controller="Ctrl">
{{objs.key}} - {{objs.value}}
</div>
</div>
</body>
</html>
I have tried this example with several small variants taken from tutorials yet it is still not working. Any help ?
Thanks!
What you get back from query() is an array so you should loop over it with ng-repeat
<div ng-app="myApp">
<div ng-controller="Ctrl">
<ul>
<li ng-repeat="obj in objs">{{obj.key}} - {{obj.value}}</li>
</ul>
</div>
</div>
First of all, let's organize your code a bit:
var app = angular.module('myApp',['ngResource']);
// Controllers get their dependencies injected, as long as you don't minify your code and lose variable names.
app.controller('Ctrl', function($scope, $resource) {
$scope.objs = []; // We initialize the variable for the view not to break.
// For the query example, you don't need to define the method explicitly, it is already defined for you.
var Geonames = $resource('http://localhost:8080/rest-application/rest/json');
// Resource methods use promises, read more about them here: http://docs.angularjs.org/api/ng/service/$q
Geonames.query({}, function(arrayResult) {
$scope.objs = arrayResult;
});
});
You have to adjust your html code with an ng-repeat directive to handle each item of your array:
<body>
<div ng-app="myApp">
<div ng-controller="Ctrl">
<!-- object is a reference for each item in the $scope.objs array-->
<span ng-repeat="object in objs">
{{object.key}} - {{object.value}}
</span>
</div>
</div>
</body>