how to pass parameter from nodejs to angularjs controller? - angularjs

I have this in nodejs
res.render('pages/dist/reset', {token:req.params.token});
and i can read it in reset.mustache
<body ng-app="eyeApp" ng-controller="ResetController">
<div id="wrapper">
<div id="layout-static">
<div class="static-content-wrapper">
<div class="static-content">
<div id="wrap" ui-view class="mainview-animation animated"></div>
<!--wrap -->
</div>
<footer role="contentinfo" ng-show="!layoutLoading" ng-cloak>
<div class="clearfix">
<button class="pull-right btn btn-default toUp btn-sm hidden-print" back-to-top style="padding: 1px 10px;"><i class="fa fa-angle-up"></i></button>
</div>
</footer>
</div>
</div>
</div>
{{token}}
</body>
Controller from this file is ResetController.
ResetController:
angular
.module('telcoserv.eye.reset', [
'telcoserv.core.services'
])
.controller('ResetController', ['$scope', '$theme','$http','$state','$window','$stateParams', function($scope,$theme,$http,$state,$window,$stateParams) {
'use strict';
$scope.submit = function(){
alert('123');
alert($scope.token);
}
}]);
alert($scope.token) is undefined.
when i say {{token}} in reset.mustache i can read value but $scope.token i can not read in resetController. Why??

$scope.submit = function(){
alert('123');
alert($scope.token);
$http({
method:'',
data: {json : data}
url: ''
}).then(function(response) {
//Success response
}, function(error) {
//Failed response
});
}
use $http to call your api. in method you can put GET, POST, PUT, DELETE, OPTIONS according to your api.
put your URL.
Put your request body in data as JSON only applicable for PUT, POST, DELETE.

If you don't want to initialize some ways to achieve this and get that as parameter
1. Create a constant service for getting token and inject it as a parameter in your controller . you can refer to this article how to create the constant service
https://lostechies.com/gabrielschenker/2014/01/14/angularjspart-9-values-and-constants/
2.On the route definition of the app , make use of the resolve in the route of the page using this controller and use of the same parameter and inject it as a dependency in your controller.

Related

making a url with the $http using routing params error

Below is the link of my file. I was unable to generate a url from the existing url generated from $http, by using $parent.$index and $index as ids from routing, please help: Plunker
I have applied the same kind of functionality to another application it worked have a look at this Plunker
Inside the loadSingleMatch() function error in updating the url inside the $http
error image:-
Code
app.controller("selfController", ['$http', '$routeParams',
function($http, $routeParams) {
//create a context
var main = this;
this.parentId = $routeParams.parent;
this.childId = $routeParams.child;
console.log(this.parentId);
console.log(this.childId);
this.urlOne = "https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json";
this.urlTwo = "https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json";
this.loadSingleMatch = function() {
$http({
method: 'GET',
url: main.urlOne + '/' + main.parentId + '/' + main.childId
}).then(function successCallback(response) {
main.matchData = response.data.rounds[main.parentId].matches[main.childId];
console.log(main.matchData);
}, function errorCallback(response) {
console.log(response);
});
}
}
]);
The a tag should be inside the second ng-repeat:
<div class="w3-row w3-hover-shadow w3-hover-border-black w3-border w3-white w3-padding-16" ng-repeat="x in matchDay.matches">
<a ng-href="#/indiTeam/{{$parent.$index}}/{{$index}}" >
<div class="w3-small">
<div class="w3-col s6 ">
{{x.team1.code}} vs {{x.team2.code}}
</div>
<div class="w3-col s6">
<div class="w3-padding-small">
{{ x.date | date: 'shortDate'}}
({{$parent.$index}} {{$index}})
</div>
</div>
</div>
</div>
</a>
</div>
See modified plunker:
https://plnkr.co/edit/PeqUHIZVC0HsqdjLkdOo?p=preview
Finally found out the answer to my question
the url inside the $http should not be changed only the response inside of it needs to be changed
the url: main.urlOne is the change that bought the output as expected

AngularJS Codeigniter base_url path settings

I am creating a website with Codeigniter 3 and AngularJs. While delevolping i have faced some issues with base url in codeigniter. Im attaching an image file of my directory struture.
In my mainpage(views/home.php) i put a ng-view for loading different pages. Here i am using angularjs ngRoute for routing.
Here is my code.
var myApp = angular.module("myApp",["ui.bootstrap","ui.router","ngRoute"]);
myApp.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "application/pages/mainpage.php"
})
.when("/about", {
templateUrl : "application/pages/about.html"
})
.when("/services", {
templateUrl : "application/pages/services.html"
})
.otherwise("/",{
templateUrl: "application/pages/mainpage.php"
});
});
Inside that mainpage.php i am listing some profile contents(dummy contents) which is residing inside a json file(datas/data.json). And all the content were listing. And inside this listing i placed a button with ng-click="myName"
Here is the code:
<div class="container" ng-controller="ListController">
<div class="row">
<div class="col-lg-12 text-center">
<h1>Starter Template</h1>
<p class="lead">Complete with pre-defined file paths that you won't have to change</p>
<div class="row">
<div class="col-sm-6 col-md-4 wow zoomIn" data-wow-delay="0.5s" ng-repeat="items in artists">
<div class="thumbnail">
<img ng-src="{{settings.base_url}}/application/assets/images/profile/{{items.shortname}}.jpg" alt="...">
<div class="caption">
<h3>{{items.name}}</h3>
<p>{{items.bio}}</p>
<p>Button Button</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
All my js code were wriiten in app.js(assets/js/app.js) including Angular Js. In this js file i have setup a base_url variable same as in codeigniter config.php file
$config['base_url'] = 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/';
inside app.js
var base_url= 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/'
When i click on my button with ng-click="myName" i want to get a controller(Codeigniter controller) and want to execute a function inside that controller. Here iam using auth.php(controllers/auth.php) and function name as functionOne();
public function functionOne()
{
/*$this->load->view('home1');*/
echo "hai";
}
For that iam using $hhtp.post and var base_url for path. But i didnt get that output and it is not passing to that controller.
myApp.controller('ListController', ['$scope', '$http', 'settings', function($scope, $http) {
$http.get('application/datas/data.json').success(function(data) {
$scope.artists = data;
});
$scope.myName = function() {
alert("hai1");
/**/
$http.post(base_url + 'auth/functionOne').success(function(response) {
$scope.data = response
console.log($scope.data);
alert($scope.data);
});
}
}]);
ng-click="myName" function works fine. But it is not passing to the function functionOne inside that controller auth.php. I think the issue is probably with the base_url path. If any one knows this plz help me to solve this issue.
Well, I don't know it this will help you, but this is how I am doing it:
I have this function in a service:
saveFunction: function(obj, user, securityToken){
return $http({
method: 'POST',
url: 'index.php/controller/saveFUnction',
data: $.param({
postID: obj.id ,
csrfTokenName: securityToken,
postName: obj.name,
.....
userID: user.id
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
if your csrfToken is active in codeigniter config, you need to pass it in your form, as hidden type field. Also, you must set the content type in the headers.

$Scope doesn't work on subpage

this is my controller,
.state('tabs.urunler',{
url:'/urunler',
views:{
'urunler-tab':{
templateUrl:'pages/urunler.html',
controller:'MyCtrl'
}
}
})
.state('tabs.detail',{
url:'/urunler/:aId',
views:{
'urunler-tab' : {
templateUrl:'pages/urunlerDetail.html',
controller : 'MyCtrl'
}
}
})
this is POST method.
$http({
url : apiAddress + 'getUrunler',
method : 'POST',
data : {type}
}).then(function successCallback(response){
$scope.urunler = response.data;
console.log($scope.urunler);
},function errorCallback(response){
console.log("error");
});
this is my urunDetails.html
<ion-item ng-repeat="urun in urunler">
{{urun.title}}
<div class="list">
{{urun.brand}}
<a class="item item-thumbnail-left">
<img src ="{{urun.picture}}">
<h2>{{urun.brand}}</h2>
<p>{{urun.title}}</p>
</a>
</div>
this is the Urun.html
<ion-item ng-repeat="urun in urunler">
<div class="list">
<a class="item item-thumbnail-left" ng-click="changeUrun('Alix Avien')" href="#/tab/urunler/{{urun.title}}">
<img src ="{{urun.picture}}">
<h2>{{urun.brand}}</h2>
<p>{{urun.title}}</p>
</a>
</div>
</ion-item>
The problem is , I can reach {{urun}} in Urun.html, but when I go to subpage of urun.html which is urundetails.html, $scope doesn't work :/. I've looked the response data after reached the urunDetails.html by writing console.log(); Data is coming but I can not see data on the urunDetails.html page. Thanks for help !!
This issue is because you are binding data to the scope variable outside angular scope digest cycle. For this scenario you will have to manually trigger the digest cycle.
There are no. of ways to trigger the digest cycle manually.
I will suggest just use $timeout(function(){}, 0); after $scope.urunler = response.data. This will basically trigger the digest cycle once more by taking care of any clashes if there is any digest cycle already running.
Your two states use the same controller, but each controller instance seems to have its own $scope.
I experimented with this here in this plunkr: https://plnkr.co/edit/qGO3pIDHezym71l7jygU?p=preview
angular.module('myApp', []);
angular.module('myApp').controller('ctrl1', ctrl1);
ctrl1.$inject = ['$scope'];
function ctrl1($scope){
$scope.test = 'Something';
$scope.change = function(){
$scope.test = 'Something else';
}
}
and
<body ng-app="myApp">
<div ng-controller="ctrl1">
<p>
{{test}}
</p>
<button ng-click="change()">Click me!</button>
</div>
<div ng-controller="ctrl1">
<p>
{{test}}
</p>
</div>
</body>
The 'change' function only changes the scope variable in the instance where it is called. My best guess is something similar is happening in your case.
You probably want to use some kind of service to provide your controller with the correct data.
Maybe that helps you with your problem, this is just my best guess though. I unfortunately can't really see what you are trying to do with your provided code samples.

$http.get not executing functions on success

I am doing my first Angular project (ionic framework) where i have to get some data from database and on success I havet to
store it in a variable
navigate to a page where this variable is used.
The page is navigating, but data are not sent.
Here is my search.html code:
<body ng-app="starter" ng-controller="ListCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Real Estate</h1>
</ion-header-bar>
<ion-content>
<h4 align="center"> Enter Place or Pincode </h4>
<div class="list list-inset" >
<label class="item item-input">
<input type="text" name="place" ng-model="data.place" value="" placeholder="Place" ng-focus="$scope.placefocus=true;data.pincode=null" ng-blur="$scope.placefocus=false" ng-disabled = "$scope.pincodefocus">
</label>
<label class="item item-input">
<input type="number" name="pincode" ng-model="data.pincode" value="" placeholder="Pin Code" ng-focus="$scope.pincodefocus=true;data.place=null" ng-blur="$scope.pincodefocus=false" ng-disabled="$scope.placefocus">
</label>
</div>
<button class="button button-block button-positive" ng-click="getdata()">
Search
</button>
</ion-content>
</ion-pane>
</body>
And here is my controller code :
app.controller('ListCtrl',function($scope,$http,$location,$window){
$scope.data = {};
$scope.getdata = function(){
//alert($scope.data.place);
$http.get("http://localhost/angular/data.php")
//,{'place':$scope.data.place,'pincode':$scope.data.pincode})
.success(function(response,status,headers,config){
alert(response);
$scope.datas=response;
$scope.navig('/show.html');
})
}
$scope.navig = function(url){
$window.location.href=url;
};
});
and here is my show.html page :
<ion-content>
<div class="list card" ng-repeat="site in datas">
<div class="item item-body">
<a href="#" class="subdued"><img class="full-image" src="img/{{site.image}}" height="150px">
<p>
RS.{{site.price}} &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <span> {{site.square_feet}} sq.ft &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</span><span>{{site.bed}} BHK</span>
</p>
</a>
</div>
</div>
</ion-content>
alert(response) in the controller code alerts [object Object],[object Object],[object Object]
But the output page (show.html) is blank
If I call navig("/show.html") directly from the button click (in search.html) instead of getdata() and change the controller code to the below one, I am getting the result: (But I cannot execute this way because I have to get data from database for particular place and pincode entered)
app.controller('ListCtrl',function($scope,$http,$location,$window){
$scope.data = {};
$http.get("http://localhost/angular/data.php")
//,{'place':$scope.data.place,'pincode':$scope.data.pincode})
.success(function(response,status,headers,config){
alert(response);
$scope.datas=response;
})
$scope.navig = function(url){
$window.location.href=url;
};
});
Don't use the success function, use the .then() function.The code below is from the angular documentation.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Here is the text from the Documentation
Deprecation Notice
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
$scope works with in controller only! Instead of $scope use $rootScope.
It might be the promise.
Why don't you try this.
app.controller('ListCtrl',function($scope,$http,$location,$window){
$scope.data = {};
$http.get("http://localhost/angular/data.php")
//,{'place':$scope.data.place,'pincode':$scope.data.pincode})
.then(function(response){
alert(response);
$scope.datas=response;
})
$scope.navig = function(url){
$window.location.href=url;
};
});

AngularJS: How to call function on onsubmit inside the controller as ng-submit

I am developing mobile app in angularJS, ionic framework and cordova. I am having a scenario where form data i am submitting to server and when server respond me with the status as 200 i am navigating user to the confirmation page. My code is:
<ion-view title="Fill the Form" ng-controller="formSubmit">
<ion-content class="padding-vertical" ng-repeat="htmlValue in HTML">
<form name="fieldForm" id="{{htmlValue.Id}}" method="post" onsubmit="submitFormData($(this).serialize(), $(this).attr('id'))">
<div class="bootstrap" ng-bind-html="htmlValue.Html | unsafe">
</div>
<div class="padding">
<button class="button button-block button-calm">
Submit
</button>
</div>
</form>
<div class="clearfix"></div>
</ion-content>
The function i have written below the index.html page before the body ends.
<script type="text/javascript">
function submitFormData(serializedData,value){
var data = serializedData;
$.ajax({
url: base_url+"put/putFormFilledRawData.php?id="+value,
type: "POST",
data: data,
success: function(tableData){
alert('success');
}});
return false;
};
</script>
Thing is when response arrives as 200 i have to navigate through $state.go() function and for that this function needs to be accessed inside the controller. For that i tried ng-submit at the place of onsubmit but is always shows me error: submitFormData is not a function. How to make it work inside controller from front view forms submit call?
The more angular way of doing it is following:
HTML :
<ion-view title="Fill the Form" ng-controller="formSubmit">
<ion-content class="padding-vertical" ng-repeat="htmlValue in HTML">
<form name="fieldForm" id="{{htmlValue.Id}}" ng-submit="submitFormData(htmlValue)">
<div class="bootstrap" ng-bind-html="htmlValue.Html | unsafe">
</div>
<div class="padding">
<button class="button button-block button-calm">
Submit
</button>
</div>
</form>
<div class="clearfix"></div>
</ion-content>
Controller :
angular.module('formSubmitModule', [])
.controller('formSubmit', ['$scope', function($scope, $http) {
$scope.HTML = []; //Assuming you are getting the array of objects here
$scope.submitFormData= function(formObj) {
$http({
url: '/someUrl',
method: "POST",
params: {paramA: valueA, paramB: valueB}
});
};
(Another flavour of $http service to pass the params in the URL)
This is how you should be making the ajax call and POST the form data in angularJS.
P.S. You can also explore the 'promises' that are returned by the $http service of the angularjs rather then dealing with success and error callbacks.
Look at the documentation of ng-submit
You need to create a controller or a directive and bind the function to the $scope.
Check below example
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>

Resources