Posting data to my controller for API call - Ionic - angularjs

Trying to get my form inputs into my controller so that I can pass them in my API call.
I have this form:
<ion-content class="has-subheader">
<form ng-submit="storeProject()">
<div class="list">
<label class="item item-input">
<span class="input-label">Title</span>
<input type="text" ng-model="projectData.title">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit">Create Project</button>
</label>
</div>
</form>
</ion-content>
I then have this controller:
.controller('ProjectCtrl', function($scope, $auth, $http, $ionicPopup, $rootScope) {
$scope.projectData = {};
$scope.storeProject = function(projectData) {
console.log("add project: ", $scope.projectData);
};
})
And this in my app.js:
.state('app.new_project', {
url: '/projects/new',
data: {
permissions: {
except: ['anonymous'],
redirectTo: 'app.auth'
}
},
views: {
'menuContent': {
templateUrl: 'templates/new_project.html',
controller: 'ProjectCtrl'
}
}
});
I have my API working great, but just need to be able to get my values from the form to post.
Need to be able to do projectData.title etc.
I always get undefined in the log.

Replace
$scope.storeProject = function(projectData) {
by
$scope.storeProject = function() {
Or replace
ng-submit="storeProject()"
by
ng-submit="storeProject(projectData)"
That said, I don't see how your posted code could log undefined. My guess is that your actual code is
console.log("add project: ", projectData);

Related

controllerAs method is not getting called when others are

I' trying out firebase 3 with my Ionic app. (I just made one to mess with - so I figure i might as well do everything right from the beginning, such as using ControllerAs notation)
everything in the controller works fine. just the logUserOut method doesnt fire - at all! I'm at a loss.
controller:
.controller('DashCtrl', function($scope, $ionicModal, DataService, AuthService) {
var ctrl = this;
ctrl.icons = [];
//// SERVICE GETS
ctrl.allIcons = DataService.icons();
ctrl.pages = DataService.pages();
////
//// FILTER INFORMATION
ctrl.loadIcons = function() {
console.log(ctrl.pages)
for (icon in ctrl.allIcons) {
var i = ctrl.allIcons[icon];
// console.log(i)
if(i.active){
ctrl.icons.push(i);
}
}
};
////
//// ACTIONS
ctrl.logUserOut = function(){
console.log('this is not being called')
// AuthService.logout();
};
////
});
html:
<ion-modal-view>
<ion-pane >
<ion-content scroll="false" >
<section class = "modal-container">
<div class="item modal-header">
<button class="button button-left button-icon light ion-android-close" ng-click="ctrl.closeProfileModal()"></button>
<div class="light text-center">
<button class="button button-clear" ng-click="controller.closeProfileModal()">
<img class="avatar-modal" src="img/mike.png">
</button>
</div>
</div>
<div class = "row modal-profile-row">
<div class = "col">
<button class="button button-clear">
<span class="title light">Personal Info</span>
</button>
</div>
</div>
<div class = "row modal-profile-row">
<div class = "col">
<button class="button button-clear" ng-click="ctrl.logUserOut()">
<span class="title light">Sign Out</span>
</button>
</div>
</div>
</section>
</ion-content>
</ion-pane>
</ion-modal-view>
app.js:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl',
controllerAs: 'ctrl'
}
}
})
EDIT:
It turns out the problem was with Sublime Text : for some reason, there was a weird cache issue - I was editing the file but the changes weren't recognized. I'm Glad that I asked because now I am using 'controllerAs:' in the $stateProvider and not 'controller: someController as something'. Thank you all for your help!
In your app.js change to:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl',
controllerAs: 'ctrl' // <-- here
}
}
})
I'll explain a little more. In your controller you set a variable to 'this'. The name you use can be anything such as wowItsAVariable = this; however when you attach your controller you can use a completely different name such as controllerAs: 'wowSomeOtherName' and that is how you reference it in your html. The name doesn't matter and I would stay away from using names such as 'controller' as that doesn't tell anyone what controller you're trying to reference. Hope that helps.

$scope not displaying data

The $scope data is not displaying on the page.
I have 2 views that are using the same controller.
I have this view, and I'm clicking the edit issue button
<div class="container" data-ng-init="adminInit()">
<div class="row">
<div class="col-lg-12">
<div class="page-header text-center">
<h1>Issues Admin</h1>
<button type="button" class="btn btn-primary" ui-sref="add-issue">
Add Issue
</button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3>Current Issues</h3>
<ul ng-repeat="issue in issues">
<li>
<strong>{{issue.title}}</strong> - Current Status:
<strong>{{issue.status}}</strong>
<div ng-hide="true" class="btn btn-xs btn-primary glyphicon glyphicon-pencil" ng-click="editIssue(issue._id)"></div>
<div class="btn btn-xs btn-primary glyphicon glyphicon-pencil" ng-click="editIssue(issue._id)"></div>
<div class="btn btn-xs btn-danger glyphicon glyphicon-remove" ng-click="deleteIssue(issue._id)"></div>
</li>
<ul>
<li>{{issue.description}}</li>
<li>Issue Logged at: {{issue.timestamp | date:'MM/dd/yyyy # h:mma'}}</li>
</ul>
</ul>
</div>
</div>
</div>
And this in my controller
$scope.editIssue = function(id) {
$state.go('edit-issue');
$http.get(Configuration.API + 'api/issue/' + id)
.then(function successCallback(response) {
$scope.issueToEdit = response.data;
console.log($scope.issueToEdit);
});
};
then the edit-issue view
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="page-header text-center">
<h1>Edit Issue</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form name="frm" ng-submit="updateIssue()">
<div class="form-group">
<label for="editIssueTitle">Issue Title</label>
<input type="text" name="editIssueTitle" id="editIssueTitle" class="form-control" ng-model="issueToEdit.title" required/>
</div>
<div class="form-group">
<label for="editIssueDesc">Issue Description</label>
<textarea name="editIssueDesc" id="editIssueDesc" class="form-control" cols="60" rows="16" ng-model="issueToEdit.description" required></textarea>
</div>
<div class="form-group">
<label for="editIssueStatus">Issue Status</label>
<select name="editIssueStatus" id="editIssueStatus" class="form-control" ng-model="issueToEdit.status" required>
<option value="Identified">Identified</option>
<option value="Investigating">Investigating</option>
<option value="Monitoring">Monitoring</option>
<option value="Resolved">Resolved</option>
</select>
</div>
<button class="btn btn-default" ng-disabled="frm.$invalid">Go</button>
</form>
</div>
</div>
</div>
But the issueToEdit data is never displayed
The console.log line displays the right data
{
"_id": "58135b6e3987b8a90c4fc15b"
"title": "Test"
"description": "Testset"
"timestamp": "2016-10-28T14:06:38.284Z"
"status": "Monitoring"
"__v": 0
}
Any idea why this is happening?
EDIT: Let me clarify a little, when I land on the edit-issue page, I want the issueToEdit data to displayed in the form so that I can then update the info and then save it.
EDIT2: Here is my full controller and app.js
app.controller('issuesController', ['$scope', '$http', '$state', '$interval', 'auth', 'Configuration', function($scope, $http, $state, $interval, auth, Configuration) {
$scope.isLoggedIn = auth.isLoggedIn;
$scope.getIssues = function() {
console.log('retrieving issues');
$http.get(Configuration.API + 'api/issue')
.success(function(data) {
$scope.issues = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.addIssue = function() {
var nIssue = {
'title': $scope.newissue.title,
'description': $scope.newissue.description,
'timestamp': new Date(),
'status': $scope.newissue.status
}
$http.post(Configuration.API + 'api/issue', nIssue)
.success(function(data) {
$state.go('admin');
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.editIssue = function(id) {
$state.go('edit-issue');
$http.get(Configuration.API + 'api/issue/' + id)
.then(function successCallback(response) {
$scope.issueToEdit = response.data;
console.log($scope.issueToEdit);
});
};
$scope.updateIssue = function() {
//ToDo add this logic
};
$scope.deleteIssue = function(id) {
$http.delete(Configuration.API + 'api/issue/' + id)
.success(function(data) {
$scope.issues = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.adminInit = function() {
$scope.getIssues();
$interval($scope.getIssues, 60000);
};
$scope.issueInit = function() {
$scope.getIssues();
$interval($scope.getIssues, 60000);
$(".devInfo").text(navigator.userAgent);
$(".flashVersion").text(FlashDetect.raw);
};
}]);
app.js
var app = angular.module('supportWebsite', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/articles');
$stateProvider
.state('home', {
url: '/',
templateUrl: '/pages/issues/index.html',
controller: 'issuesController'
})
.state('admin', {
url: '/admin',
templateUrl: '/pages/issues/admin/index.html',
controller: 'issuesController',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
})
.state('add-issue', {
url: '/admin/add-issue',
templateUrl: '/pages/issues/admin/add.html',
controller: 'issuesController',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
})
.state('edit-issue', {
url: '/admin/edit-issue',
templateUrl: '/pages/issues/admin/edit.html',
controller: 'issuesController',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
});
$locationProvider.html5Mode(true);
}]);
Your method tells the $state service to go to another state. That will replace the view by the view associated with the new state, create a new $scope, and a new controller instance using this new $scope.
So whatever you put in the $scope of the current controller is irrelevant and useless: the other state uses another $scope and another controller.
You need to pass the ID of the issue to edit as a parameter of the new state. And the controller of this new state (or one of its resolve functions) should use that ID to get the issue to edit.
If you want to stay on the same view, using the same controller and the same scope, then you shouldn't navigate to another state.

AngularJS change location is not working

I'm new in ionic
I'm trying to do a simple switch between two views in a login app:
index.html
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Login App</h1>
</ion-header-bar>
<ion-content>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="data.email">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
</div>
<button class="button button-block button-calm" ng-click="postLogin()">Login</button>
</ion-content>
</ion-pane>
logincontroller.js
app.controller('loginCtrl', function ($scope,$http,$location)
{
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password
};
console.log('bonjour');
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
$location.path('/map');
},
function(response){
// failure callback
console.log('error');
$location.path('/index');
}
);
}
When I click on a button Login the url change but the page doesn't change
Could someone tell me how do I solve this ? Thanks in advance :)
In your app.js add a state for map like this (with your own templateUrl and controller value). Make sure to add $stateProvider in the config(). Also, include ui.router to your dependencies. Something like this:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.directives', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider){
$stateProvider
.state('map', {
url: '/map',
templateUrl: 'app/views/map.html',
controller: 'MapController'
});
...
And in your index.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
Try this
app.controller('loginCtrl', function ($scope,$http,$location,$state) {
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password
};
console.log('bonjour');
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
$location.path('/map');
},
function(response){
// failure callback
console.log('error');
$state.go('main');
});
})
Add a state in app.js
.config(function($stateProvider,$urlRouterProvider){
.state('main', {
url:'/main',
templateUrl:'templates/main.html',
controller:'yourCtrl'
})
$urlRouterProvider.otherwise('/index');
})
Now make in template folder make a page for named main.html

angularjs and ui-router - controller not working

The full source code.
I don't understand why $scope not working in my LoginGuideCtrl controller. I try click on login button and should show a <p> with new data but the $scope is not updating...
DonĀ“t forget I'm trying to achieve a modular design.
I have the following code:
guides.js
var guides = angular.module('main.guides', ['ui.router']).config(function ($stateProvider) {
$stateProvider.
state('guides.login', {
url: '/login',
templateUrl: 'modules/guides/views/login.html',
controller: 'LoginGuideCtrl'
}).
...
state('guides.mobile', {
url: '/web',
template: '<div>guildes mobile</div>',
controller: 'ListCtrl'
});
});
controller.js
var guides = angular.module('main.guides');
guides.controller('IndexCtrl', function() {
console.log('Index');
})
.controller('LoginGuideCtrl', function($scope) {
console.log('feck');
$scope.checkLogin = function(){
$scope.message = "Welcome "+$scope.name+"!"
};
})
.controller('ListCtrl', function() {
console.log('List');
})
login.html
<div class="form-group col-sm-2">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr" ng-model="name">
</div>
<div class="form-group col-sm-2">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" ng-model="password">
</div>
<button type="button" class="btn btn-default" ng-click="checkLogin()">Login</button>
<p ng-model="message"></p>
ng-model is used with <input> tags to capture user input, by two way binding with your model value.
Since a <p> tag does not collect user input, it won't work with ng-model. Instead just do a one way binding with the value using the curly brackets:
<p>{{message}}</p>

Angular updating and clearing factory variables

I'm creating a single page app in which a user searches for a term, the result gets saved in a variable, and a new page is routed that displays the result. I have this functionality working, however I want the variable to be cleared when the user returns to the previous page and most importantly when the user logs out. What's the proper way to do this? I want the factory to save things for certain pages that I want, and clear them for certain pages I don't want like "home" or "logout".
Factory:
angular.module('firstApp')
.factory('fact', function () {
var service = {};
var _information = 'Default Info';
service.setInformation = function(info){
_information = info;
}
service.getInformation = function(){
return _information;
}
return service;
});
Controller:
angular.module('firstApp')
.controller('InformationCtrl', function($scope, $http, $location, fact) {
$scope.message = 'Hello';
$scope.result = fact.getInformation();
$scope.sub = function(form) {
console.log($scope.name);
$scope.submitted = true;
$http.get('/wiki', {
params: {
name: $scope.name,
}
}).success(function(result) {
console.log("success!");
$scope.result = result;
fact.setInformation(result);
$location.path('/informationdisplay');
});;
}
});
Routes
angular.module('firstApp')
.config(function ($routeProvider) {
$routeProvider
.when('/information', {
templateUrl: 'app/information/input.html',
controller: 'InformationCtrl',
authenticate : true
})
.when('/informationdisplay', {
templateUrl: 'app/information/results.html',
controller: 'InformationCtrl',
authenticate : true
});
});
input.html
<div class="row">
<div class="col-md-6 col-md-offset-3 text-center">
<p>{{result}}</p>
<form class="form" name="form" ng-submit="sub(form)" novalidate>
<input type="text" name="name" placeholder="Name" class="form-control" ng-model="name">
</br>
<button class="btn btn-success" type="submit" class="btn btn-info">Check</button>
</div>
</div>
results.html
<div ng-include="'components/navbar/navbar.html'"></div>
<div class="row">
<div class="col-sm-4 col-sm-offset-4">
<h2>Information Results</h2>
<p>{{result}}</p>
</div>
</div>
</div>
If you want it to wipe the value when they change routes (which logout should change routes also, I assume), you can watch the $routeChangeStart event and have it wipe the value whenever it occurs. You put that function in the module.run block:
app.run(function ($rootScope, fact) {
$rootScope.$on("$routeChangeStart",function(event, next, current){
fact.setInformation(null);
});
});

Resources