how to catch nodejs api data in AngularJS page? - angularjs

this is api code i am using and passing some parameters
app.get('/opner',function (req, res) {
res.sendFile(
path.join(__dirname, './','dist', 'index.html'),
{user: req.session.user,value1:req.session.value1}
);
});
i am serving angular with the same api.
in this case in ejs i can directly access this user and value1
with <%= user %> like this. but how to use the same in angular app
<div class="form-group">
<h4> value 1:</h4>
<textarea class="form-control" rows="8" ng-model="tx.data"></textarea>
</div>
<div class="form-group">
<h4>user:</h4>
<input class="form-control" type="text" ng-model="tx.user"/>
</div>
so i want to render this page with value1 and user values present.
so how to read and display in angular?

The node function res.sendFile is not the same as res.render.
res.render is for rendering EJS (or pug, or other pre-renderer).
res.sendFile only send file.
You cannot use the second argument of res.sendFile to send data alongside your index.html like you would do in EJS
The right way to do it would be to create another express route (like /getUser), and to send the json in this route with res.json({req.session.user,value1:req.session.value1})
You will then have to do a ajax request in Angular.
if you use Angular 1.x, I think the service name is http
for Angular 2+, the service name is HttpClient.
Once you have queryed the data, you can show it in your angular template like so:
<h4> value 1: {{tx.data}}</h4>
supposing you put your data on the $scope.tx.data object (angular 1.x) or as this.tx = {data : data, user : user} on the class of your component (angular 2+)

Like Felix says is better to make your own GET route to get the data via http request, but ifyou want to avoid that you need to use a template engine (like EJS or Pug) because Angular is loaded after template rendering.
res.render('yourPath/index.html', {user: req.session.user, value1: req.session.value1});
And in your AngularJS side you can use ng-init. EJS example:
<div class="form-group" ng-init="tx.data = '<%= value1 %>';tx.user = '<%= user %>'">
<h4> value 1:</h4>
<textarea class="form-control" rows="8" ng-model="tx.data"></textarea>
</div>
<div class="form-group">
<h4>user:</h4>
<input class="form-control" type="text" ng-model="tx.user"/>
</div>
PUG Interpolation example:
<div class="form-group" ng-init="tx.data = '!{value1}';tx.user = '!{user}">
<h4> value 1:</h4>
<textarea class="form-control" rows="8" ng-model="tx.data"></textarea>
</div>
<div class="form-group">
<h4>user:</h4>
<input class="form-control" type="text" ng-model="tx.user"/>
</div>

Related

Get pristine value in Angular controller

I need to be able to see in the Angular controller if the datepicker is pristine or not. Tried all sorts of things including sending the pristine value in a method but cannot get this value. Below is the view code:
<form name="myForm">
<!-- Datepicker From -->
<div class="small-6 medium-5 large-2 columns" ng-if="vm.subViewActive">
<div class="input-group">
<input name="valuationDatePickerFrom" ng-model="name" type="text" class="datepicker" id="valuationDatePickerFrom" placeholder="DD/MM/YYYY" pikaday="vm.datePickerFrom" on-select="vm.selectStartDate(pikaday)" year-range="{{ vm.yearRange }}" >
<div class="input-group-addon">
<label for="valuationDatePickerFrom" class="postfix">
<i class="fa fa-calendar"></i> From
</label>
</div>
</div>
</div>
</form>
and then I also tried :
var isPristine = $scope.myForm.valuationDatePickerFrom.$pristine;
console.log(isPristine);
in my controller but cannot get the pristine value. Read lots of posts here but mainly to do with CSS classes and front-end control or setting the pristine state from the backend not getting or checking the pristine state.
Thanks anybody that can help.
You are using:
var isPristine = $scope.myForm.valuationDatePickerFrom.$pristine;
but your form's name is not myForm.
Change <input name="name"... <input name="valuationDatePickerFrom"...
Then you can use:
var isPristine = $scope.userForm.valuationDatePickerFrom.$pristine;
Also, the controller is getting called before the view is created, so no myForm exists at the time the controller runs. Try adding a $timeout like so:
$timeout(function() {
var isPristine = $scope.userForm.valuationDatePickerFrom.$pristine;
console.log(isPristine);
}, 100);
plunkr
The above solution only works on page load, but you need to know this value when the page is being used. Instead pass the value to the controller when an action happens:
<form name="myForm">
<input type="text" name="valuationDatePickerFrom" ng-model="valuationDatePicker" ng-blur="alerty(myForm.$pristine)">
</form>
.controller('MainController', function($scope) {
$scope.alerty = function(isPristine){
alert('isPristine: ' + isPristine);
};
https://plnkr.co/edit/f0EWvYmoXCn8UOH3QCfE?p=preview

Why is my AngularJS module never loaded?

I am an AngularJS newbie, and am having difficulty getting an AngularJS form to work correctly. Chrome Dev Tools tells me my module is not being loaded.
Below is my html; it is a div within a Wordpress template:
<div ng-app="contact" style="float: left;">
<form method="post" name="form" role="form" ng-controller="ContactFormController" ng-submit="form.$valid && sendMessage(input)" novalidate>
<p ng-show="success">Thanks for getting in touch!</p>
<p ng-show="error">Something wrong happened!, please try again.</p>
<legend>Contact</legend>
<fieldset>
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" ng-model="input.name" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" ng-model="input.email" required>
</div>
<div>
<label for="messsage">Message:</label>
<textarea id="messsage" name="message" ng-model="input.message" required></textarea>
</div>
<div>
<label for="honeypot">I promise I'm not a bot</label>
<input type="text" id="honeypot" name="honeypot" ng-model="input.honeyPot">
</div>
</fieldset>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</div>
This is my angular code:
angular.module("contact", [])
.controller("ContactFormController", ['$scope', '$http', function($scope, $http) {
$scope.success = false;
$scope.error = false;
$scope.sendMessage = function( input ) {
$http({
method: 'POST',
url: 'http://alamanceforeducation.org/wp-content/themes/flex/library/scripts/processApplecartForm.php',
data: input,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success( function(data) {
if ( data.success ) {
$scope.success = true;
} else {
$scope.error = true;
}
} );
}
}]);
The code is adapted from a tutorial. Can anyone help me out with what I am doing wrong?
There's nothing wrong with your code in terms of the problem you are having. The problem is the order in which you are loading the scripts.
The order should be:
1- angular.js
2- any-angular-dependency.js
3- your-angular-app.js
this is a working copy of your code
I'm not including the form because is just to show you that it doesn't find your angular module because either you are not including it or is not loading correctly from cdn, you might want to download it to have it locally and include the <script src="angular.js"></script> tag
In order to add a new module you need to make sure that:
The JS file is properly loaded on your page together with the other modules and angular.js
The module is properly declared for example: angular.module('myModule').directive(....) is not a module declaration, because doesn't have the dependencies array like this: angular.module('myModule',[]).directive(....)
Add the dependency on the declaration of your app, or add the module as dependency of other which already is a dependency of your app:
angular.module('app',['app.my-directives']).config(...)-
angular.module('app.my-directives',[]).directive('SomeDirective',function(){})
Here I have a full example of a working application using angular-ui-route (I recommend you this routeProvider instead of the default provider, it's more expressive and robust), I hope it works for you, it has 2 states each one with different views, and several modules for directives and factories:
Images Gallery with AngularJS
Images Gallery with AngularJS Live
PS: ignore the web.js file, it's only for deploy the dist folder using Node.JS
I hope this solve your issue, please update the question with the plunker

realtime search with angularJS

I use that code (Angular JS + ngautocomplete)
<div ng-controller="autocomplete_cities">
<form id="form" role="form">
<div class="form-group move-down">
<label for="Autocomplete">Autocomplete - Cities in Canada</label>
<input type="text" id="Autocomplete" class="form-control" ng-autocomplete ng-model="result2" details="details2" options="options2"/>
</div>
<div>result: {{result2}}</div>
</form>
</div>
This code is for user search à city with an googlemaps autocomplete system. (script works)
I'v make an ajax script that request all entries where city is $result2 (script works).
My problem: I would like that ajax's script run everytime user press enter or select an autocomplete suggestions. Like onchange {{result2}} = execute ajax.

Populate array in angularJS model from view

I am building an angularJS on client side and asp.net as backend. I have a aspx repeater that generate html on server side. I want to populate and array of angular model so that it can be used to make client side interactive application.
<div ng-controller="myController">
<input type="number"id='1' ng-model="number"/>
<input type="number"id='2' ng-model="number"/>
<input type="number"id='3' ng-model="number"/>
<input type="number"id='4' ng-model="number"/>
<input type="number"id='5' ng-model="number"/>
</div>
I want to have all the numbers in an array of my model. is it possible to populate model array from the already generated html.
Make $scope.numbers an array and use ng-repeat like this: $scope.numbers = [1,2,3,4,5];
In your markup:
<div ng-controller="myController" ng-repeat="number in numbers">
<input type="number" id="number{number}" ng-model="number"/>
</div>
When you are generating html code on the server side you can use ngInit to place some data in the scope.
You could write something on the server side:
<div ng-controller="myController" ng-init="myData=[{type:'number', id:1, model:'number1'},{type:'number', id:2, model:'number2'}]">
<div>{{numbers}}</div>
<input ng-repeat="item in myData" type="{{item.type}}" id="{{item.id}}" ng-model="numbers[item.model]"/>
</div>
and your controller could look like this
app.controller('myController', function($scope) {
$scope.numbers = {};
});

Dynamic ng-model name in AngularJS form

I have an AngularJS form where I'm using ng-repeat to build the fields of the form dynamically based on another selection. I'm trying to generate the model name dynamically and am running into problems.
<div class="form-group" ng-repeat="parameter in apiParameters">
<label for="{{parameter.paramName}}" class="col-sm-2 control-label">{{parameter.paramTitle}}</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="{{parameter.paramName}}" id="{{parameter.paramName}}" ng-model="formData.parameters.{{parameter.paramName}}" placeholder="{{parameter.paramTitle}}">
</div>
</div>
What I need is it to eval to something like ng-model="formData.parameters.fooId" or ng-model="formData.parameters.barId"
The above results in an error:
Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 21 of the expression [formData.parameters.{{parameter.paramName}}] starting at [{{parameter.paramName}}].
In my controller I have:
$scope.formData = {};
$scope.formData = {
settings:
{
apiEndpoint: '',
method: 'get'
},
parameters: {}
};
I've also tried ng-model="formData.parameters.[parameter.paramName]" (based on this question How can I set a dynamic model name in AngularJS?), but that doesn't eval and fails to set the ng-model value. I'm not sure if what I'm trying to accomplish is even possible. I'm assuming I need to go through the controller to achieve what I want, but any help would be appreciated.
You just need to use hash key as model:
<div class="form-group" ng-repeat="parameter in apiParameters">
<label for="{{parameter.paramName}}" class="col-sm-2 control-label">{{parameter.paramTitle}}</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="{{parameter.paramName}}" id="{{parameter.paramName}}" ng-model="formData.parameters[parameter.paramName]" placeholder="{{parameter.paramTitle}}">
</div>
</div>
There is many other approaches, but this one are simpler than others.
I have tested this solution but it has a problem for my self. The problem is that the parameter "formData" is assigned to each iteration individually. In the other words if you insert a pre tag in every iteration you will see the value of each iteration individually and you cannot get all the formData in your controller after submitting the form.
For this I have found a very simple solution and it is the ng-init !!!!
Simply add this code to your form and before your repetitive tag. For the example of this question we will have:
<form ng-init="formData = []">
<div class="form-group" ng-repeat="parameter in apiParameters">
<label for="{{parameter.paramName}}" class="col-sm-2 control-label">{{parameter.paramTitle}}</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="{{parameter.paramName}}" id="{{parameter.paramName}}" ng-model="formData.parameters[parameter.paramName]" placeholder="{{parameter.paramTitle}}">
</div>
</div>
</form>

Resources