I have created one function
<button data-toggle="modal" ng-click="edit(school.school_ID)" data-target="#edit-data" class="btn btn-primary">Edit</button>
pass to AngularJS controller
$scope.edit = function(id)
{
$http({
method : 'GET',
url: 'mycontroller/myfun',
}).then(function(data){
console.log(data);
$scope.form = data;
});
};
accessing in mycontroller/myfun
public function myfun(id)
{
$q = $this->db->get_where('tablename', array('school_ID' =>
id));
echo json_encode($q->row());
}
Where is the problem
Related
I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
I am new in angular js. i have making ionic app useing angular js and ionic framework,
This is my service.js file.
In this i have create LoginService for Login control. but its not working.
angular.module('starter.services', ['ngCookies'])
.service('LoginService', function ($q, $http, $cookies, $rootScope) {
return {
loginUser: function (name, pw) {
var deferred = $q.defer();
var promise = deferred.promise;
var user_data = $http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php");
user_data.then(function (result) {
var user = result.data;
log(user);
console.log($rootScope.session);
})
function log(user) {
var i;
var isloggedin = false;
for (i = 0; i < user.length; i++) {
if (name == user[i].user_email && pw == user[i].password) {
isloggedin = true;
id = user[i].iduser;
$rootScope.session = id;
break;
}
}
if (isloggedin) {
deferred.resolve('Welcome ' + name + '!');
} else {
deferred.reject('Wrong credentials.');
}
}
promise.success = function (fn) {
promise.then(fn);
return promise;
}
promise.error = function (fn) {
promise.then(null, fn);
return promise;
}
return promise;
}
}
})
This is my controllers.js file
angular.module('starter.controllers', ['ngRoute','ngCookies'])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
})
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state, $cookies, $rootScope) {
$scope.data = {};
$scope.create = function () {
$state.go('signup');
}
$scope.forgot = function () {
$state.go('forgotpassword');
}
$scope.login = function () {
console.log($scope.data.user_email);
LoginService.loginUser($scope.data.user_email, $scope.data.password).success(function (data) {
var wat = $rootScope.session;
console.log(wat);
$state.go('app.dashboard');
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
})
This is my login.html
<ion-view view-title="Login" hide-nav-bar="true" name="login-view">
<ion-content ng-controller="LoginCtrl">
<div class="bar-header padding">
<h1 class="title vanimage"><img src='img/logo.png'></h1>
</div>
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" name="username" ng-model="data.user_email">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="data.password">
</label>
<label class="item">
<button class="button button-block button-positive" ng-click="login()">Log in</button>
</label>
</div>
<div class="padding">
<button class="button button-block button-positive" ng-click="create()">Registeer hier</button>
<button class="button button-block button-positive" ng-click="forgot()">Password Vergeten?</button>
</div>
</ion-content>
</ion-view>
You should put the auth logic in the backend, more secure and efficent.
This is the code I use for login in a service of a Ionic app:
login: function( loginEmail, loginPassword ) {
var deferred = $q.defer();
$http({
method: 'POST',
url: backend_url + '/auth',
// --- change content-type if needed (default = application/json)
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: { email: loginEmail, password: loginPassword }
}).then( function( result ) {
if( typeof result.data.token !== 'undefined' ) deferred.resolve( { token: result.data.token } );
else deferred.reject( { error: 'invalid_response' } );
}, function( result ) {
if( typeof result.data.error !== 'undefined' ) deferred.reject( { error: result.data.error, status: result.status } );
else deferred.reject( { error: 'invalid_login' } );
});
return deferred.promise;
},
$http always return a promice, so if you want to do it correctly in your service, using $q try smth like this:
var fn = function (method, url) {
var deferred = $q.defer();
$http(method, url)
.success(function (data) {
deferred.resolve(data);
}
.error(function (data, status) {
deferred.reject({
data: data,
status: status
});
});
return deferred.promise;
}
And if you want to call this function you should do
fn(method, url)
.then(
function(result){
... do if ok (resolve)
},
function( error) {
... do if error (reject)
}
)
You forgot to return the deferred object in your service..
This probably results in the following error:
Cannot read property then of undefined
I've made a basic example to demonstrate the $q service:
Controller - Login function
$scope.login = function login() {
LoginService.loginuser($scope.data.user_email, $scope.data.password)
.then(function onLoginSuccess(response) {
// response should contain 'success' data
$state.go('app.dashboard');
}, function onLoginFailed(error) {
var alertPopup = $ionicPopup.aler({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
Service
var API = {};
function loginUser(email, password) {
var deferred = $q.defer();
$http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php")
.then(function onUserLoggedIn(response) {
deferred.resolve(response);
}, function onLoginFailed(error) {
deffered.reject(error);
});
// Make sure to return your promise!
return deferred.promise;
}
API.loginUser = loginUser;
Sidenote: You're also using GET in your login function. For this type of operations, you would typically POST a data-object to your back-end which on his turn will return you a result.
Without the ngcontroller alias, I can fetch the data. However, when with alias, I can't. What is my mistake here?
HTML tags:
<div style="padding: 10px" id="content_dv" ng-controller="displaytopic_ctrl as f">
<div class="topic_dv" ng-repeat="t in f.topic">
<p>{{ t.MEMBER_NAME }}</p>
</div>
</div>
in app.js:
.controller('displaytopic_ctrl', ['$http', function($http) {
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d){
if(d.t=='p'){
this.topic = d.topic;
}
}).error(
function(){
console.log('Query error');
});
}]);
Due to the way JavaScript closures work, the this variable that you are using in your success callback is not the controller. The most commonly used mechanism to solve this is to create an alias for the controller which you can reference inside your callbacks.
For Example:
.controller('displaytopic_ctrl', ['$http',
function($http) {
var controller = this;
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d) {
if (d.t == 'p') {
controller.topic = d.topic;
}
}).error(
function() {
console.log('Query error');
});
}
]);
I have this template in my project:
<script type="text/ng-template" id="/challenges.html" ng-controller="ChallengeCtrl">
<main>
<h3 class="headingregister">Start challenge reeks</h3>
{{getUser()}}
<form name="startChallengesForm" ng-submit="getChallenges()">
<button type="submit" class="btn btn-primary">Doe de challenges!</button>
</form>
</main>
</script>
The getUser() function should display the current logged in users info.
This is the ChallengeCtrl:
app.controller('ChallengeCtrl', ['$scope', 'auth',
function($scope, auth) {
$scope.isLoggedIn = auth.isLoggedIn;
$scope.currentUser = auth.currentUser;
$scope.logOut = auth.logOut;
$scope.getUser = function(){
auth.getUser(auth.currentUser()).getValue(function(value){
return value;
});
};
}]);
this is auth.getUser:
auth.getUser = function(usr){
return{
getValue: function(callback){
$http({
method: 'POST',
url:'http://groep6api.herokuapp.com/user',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data : {username: usr}
}).then(function (result) {
//return result.data;
callback(result.data);
});
}
}
}
the problem is when I run the page, I see in developer tools that the function is being called over and over again, it should only display the users info.
How can I accomplish this?
Function calls in templates get executed each digest cycle. Simply fetch the user once in your controller and assign the value to the scope
auth.getUser(auth.currentUser()).getValue(function(value){
$scope.user = value;
});
and in your template, instead of {{getUser()}}
{{user}}
PROBLEM
Hello! I want to delete record using angular. So that must look like that: I click button "X" (delete) and record must be deleted.
WHAT I GOT FOR NOW
I don't know if all is correct, but there is my code:
html
<div ng-repeat="lists in listsdata.lists">
<div id="DIV_24" close-on-outside-click="div.popup_information">
<button ng-click="lists.show = !lists.show" id="MORE_BUTTON">:</button>
<div class="popup_information" ng-show="lists.show">
<button id="DELETE_BUTTON" ng-click="del_list()">X</button>
<a href="">
<button id="EDIT_BUTTON">E</button>
</a>
</div>
<a href="#/{{lists.id}}">
<div id="DIV_25">
{{lists.name}}
</div>
<div id="DIV_26">
</div>
</div></a>
</div>
angular
myApp.controller('listsController', ['$scope', '$log', '$http',
function($scope, $log, $http){
$http({
method: 'GET',
url: 'http://localhost/anydocopy/public/lists'
})
.success(function (d) {
console.log(d);
$scope.listsdata = d;
});
$scope.key = function($event){
console.log($event.keyCode);
if ($event.keyCode == 13) {
var list = {
name: $scope.listname
};
$scope.listname = '';
$http({
method: 'POST',
url: 'http://localhost/anydocopy/public/lists',
data: list
})
.success(function () {
console.log('true');
$http({
method: 'GET',
url: 'http://localhost/anydocopy/public/lists'
})
.success(function (d) {
console.log(d);
$scope.listsdata = d;
});
})
.error(function () {
console.log('false');
});
}};
$scope.del_list = function () {
$http({
method: 'DELETE',
url: 'http://localhost/anydocopy/public/lists/'+ $scope.listsdata.lists.id
});
console.log($scope.listsdata.lists)
}
}]);
laravel controller
public function delete($id)
{
$response['lists'] = Lists::findorfail($id)->delete();
return Response($response, 201);
}
laravel route
Route::delete('lists/{id}', 'ListsController#delete');
So for now when I click button, I cant set right url in agular function, because I can't get that id from $scope.listsdata.. I can get all array, but how to get only id I want? So if I click on button what is on list with id=1 so in angular function must work like method=delete and url= url+id. How to do that, please help.
Pass what you want to delete as argument. And rename lists to list, since it represents a single list:
<div ng-repeat="list in listsdata.lists">
...
<button ng-click="del_list(list)">X</button>
and
$scope.del_list = function(listToDelete) {
$http({
method: 'DELETE',
url: 'http://localhost/anydocopy/public/lists/'+ listToDelete.id
});
}
Pass argument in ng-click function you want to delete like
<div ng-repeat="list in listsdata.lists">
...
<button ng-click="del_list(list)">X</button>
</div>
you Delete function looks ike
$scope.del_list = function(selectedItem) {
$http({
method: 'DELETE',
url: 'http://localhost/anydocopy/public/lists/'+ selectedItem.id
});
console.log($scope.listsdata.lists)
}