AngularJS form post using controllers and services - javascript

jc.controller.js
angular.module('sd').controller('CJController', [
'$scope', 'jcreate', function($scope, $http, jcreate) {
return jcreate.sendJob(jobItems)(function() {
return {
create: jobItems
};
});
}
]);
jc.services.js
angular.module('sd').service('jcreate', [
"$scope", "$http", function($scope, $http) {
_cjObj = [];
_cjObj = $.param({
json: JSON.stringify(
description = $scope.name,
)
});
_create = function() {
return $http.post('URLtoBeAdded', _cjObj).success(function(response, status, headers, config) {
return alert(1);
}).error(function(response, status, headers, config) {
return alert(2);
});
};
return {
create: function(jobItems) {
return _create();
}
};
}
]);
HTML
<form class="form-horizontal" role="form" ng-submit="sendJob(jobItems)" ng-controller="CJController">
<div id="jobConnectionTab">
<div class="field-canvas">
<p class="group-lable">Connection</p>
<div class="form-group">
<label class="control-label col-sm-2" for="description">Name:</label>
<div class="col-sm-5">
<input type="name" class="form-control" id="description" placeholder="Enter description" ng-model="jobItems.name">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="reset" class="btn btn-warning" value="Clean"></button>
<button type="submit" class="btn btn-success" value="Submit"></button>
</div>
</div>
</form>
I have small application using Angular JS and I have splited to three pages as follows
Form page - HTML
controller - JS
services - JS
On page loading following error is given.
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- jcreate
After update the problem according to given instruction, following error pop:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- jcreate

You are missing $http in array:-
It should be like:
angular.module('sd').controller('CJController', [
'$scope','$http', 'jcreate', function($scope, $http, jcreate) {
..
}
Second you cannot use $scope inside the service of angular js. Just remove it and use alternative.

Related

Can't pass data from template to controller angularjs

I have a form in which I want to pass some data and post them into an URL.
What am I doing wrong here? Thanks
template.html
<div ng-controller="statusController">
<form role="form" name="form" method="post" ng-submit="rate(ratingData)">
<div class="form-group float-label-control">
<label for="title">Title</label>
<input id="title" name="title" type="text" class="form-control" placeholder="Title" ng-model="ratingData.title">
</div>
<div class="form-group float-label-control">
<label for="rating">Rating</label>
<input id="rating" name="rating" type="text" class="form-control" placeholder="Rating" ng-model="ratingData.rating">
</div>
<div class="form-group float-label-control">
<label for="review">Review</label>
<input id="review" name="review" type="text" class="form-control" placeholder="Review" required ng-model="ratingData.review">
</div>
<div class="form-group float-label-control text-center ">
<button type="submit" class="btn btn-primary" formmethod="post">Submit</button>
</div>
</form>
controller.js
angular.module('deliveryStatus', ['ngRoute'])
.component('deliveryStatus', {
templateUrl: 'components/delivery-status/delivery-status.template.html'
})
.controller('statusController', function ($http, $scope, $routeParams, Auth, $window, $timeout, $location) {
$scope.rate = function (ratingData) {
$location.url('/rating');
$http.put('/api/rating-detail', $scope.ratingData).then(function (res) {
console.log('worked');
}).catch(function (err) {
console.log('error rating');
});
};
});
Did you mean to pass the variable ratingData and then try to access it from the scope?
$http.put('/api/rating-detail', $scope.ratingData).then(function (res) {
Try
$http.put('/api/rating-detail', ratingData).then(function (res) {
I don't see ratingData initialised anywhere. See below code snippet, change it and it should work.
angular.module('deliveryStatus', ['ngRoute'])
.component('deliveryStatus', {
templateUrl: 'components/delivery-status/delivery-status.template.html'
})
.controller('statusController', function ($http, $scope, $routeParams, Auth, $window, $timeout, $location) {
$scope.ratingData = {};
$scope.rate = function (ratingData) {
console.log(ratingData)
$http.put('/api/rating-detail', $scope.ratingData).then(function (res) {
console.log('worked');
$location.url('/rating');
}).catch(function (err) {
console.log('error rating');
});
};
});

"Controller" is not registered angularjs

I have created a new project, but got a problem which I am not able to fix.
Here's my example:
I have this error :
"Error: [$controller:ctrlreg] The controller with the name 'PostController' is not registered."
Connexion.html
<section id="login" ng-controller="PostController as postCtrl">
<div class="container center-bloc">
<div class="row">
<div class="col-xs-12">
<div class="form-wrap">
<div class="text-center">
<img id="logo" style="max-width:100%;" src="img.png">
</div>
<h2 id="ResultConnexion"></h2>
<form role="form" id="login-form" ng-submit="postCtrl.Search1()" method="POST" autocomplete="off">
<div class="form-group">
<input id="userLogin" required autofocus ng-model="postCtrl.inputData.username" type="text" name="user" id="email" class="form-control" placeholder="exemple#example.com">
</div>
<div class="form-group">
<input id="userPassword" required ng-model="postCtrl.inputData.password" type="password" name="mdp" id="key" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-custom btn-lg btn-block" ng-disabled="login.$invalid" >Connexion</button>
<div class="alert alert-danger" ng-show="errorMsg">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×</button>
<span class="glyphicon glyphicon-hand-right"></span> {{errorMsg}}
</div>
<div></div>
</form>
<hr>
</div>
</div>
</div>
</div>
index. js
'use strict';
var routeApp = angular.module("routeApp", ["ngRoute"]);
routeApp.config(function($routeProvider) {
$routeProvider
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController"
})
});
var routeAppControllers = angular.module('routeAppControllers',['ngRoute']);
routeAppControllers.controller('PostController', ['$scope', '$http', function($scope, $http) {
this.postForm = function() {
var Pass = {"user":(this.inputData.username),"mdp":(this.inputData.Password)};
$http({
method: 'POST',
url: '/',
data: Pass,
headers: {'Content-Type': 'application/json'}
})
.then(function(response) {
if ( response.data.resultat == 0) {
window.location.href = '/information';
alert('hello')
} else {
$scope.errorMsg = 'Bad';
}
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}
}]);
Can anybody help?
You have two separate modules showing and neither is injected in the other.
Assuming your ng-app uses routeApp you need to inject routeAppControllers module into routeApp module
var routeApp = angular.module("routeApp", ["ngRoute", "routeAppControllers"]);
Also you only need to inject ngRoute once.
As noted in other answer you only use ng-controller when it is not declared in routing config also, or you end up with multiple controller instances
I think you should remove ng-controller="PostController as postCtrl"> from template .Because you defined it in route . and also change to below.
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController as postCtrl"
})
another tip that recommended you declare var vm = this and use vm instead of this
vm.postForm = function() {...}

Editing data in AngularJS

I just began to study angular, tried to make some kind of SPA, but faced with problem of editing data in it. The obect is visible in console, but it hasn't appear on page, what I did wrong?
Here my controller:
var app = angular.module("testModule", ['ngRoute']);
app.config(function ($routeProvider){
$routeProvider.when('/', {
templateUrl: 'pages/main.html',
controller: 'addCtrl'
})
.when('/save', {
templateUrl: 'pages/save.html',
controller: 'editCtrl'
})
.when('/edit', {
templateUrl: 'pages/edit.html',
controller: 'addCtrl'
})
})
app.service('dataService', function($http) {
var data = {};
data.list = [];
var getData = function() {
$http.get("model/data.json").then(function (response) {
data.list = response.data;
});
}
return {
getDataFromJson: getData,
getData: data,
}
});
app.controller("mainCtrl", function($scope, dataService) {
dataService.getDataFromJson();
});
app.controller("editCtrl", function($scope, dataService) {
$scope.data = dataService.getData;
$scope.editData = function(adverse){
$scope.adverse= adverse;
console.log($scope.adverse)
}
});
and the part of page:
<div class="panel">
<form name="addForm" >
<div class="well" >
<div class="form-group">
<label for="name">Name:</label>
<input type='text' id="name" class="form-control" ng-model="adverse.name" placeholder={{adverse.name}} />
<label for="shop">Shop:</label>
<input type='text' id="shop" class="form-control" ng-model="adverse.shop" placeholder="{{adverse.shop}}" />
<label for="begin">Begin:</label>
<input id="begin" class="form-control" ng-model="adverse.begin" placeholder="{{adverse.begin}}" >
<label for="end">End:</label>
<input id="end" class="form-control" ng-model="adverse.end" placeholder="{{adverse.end}}" />
<button type="submit" class="btn btn-primary btn-block add_btn" ng-click="editData(adverse)">
Edit
</button>
</div>
</div>
</form>
</div>
Also here is a screenshot: the props of object suppose to be in the inputs but it hasn't.
enter image description here
If possible can you give me an example how I can do it by another way?
Recreated your scenario in this plunker. But it works. Please have a look at this plunker where you alo can see the StateProvider which is used instead of NgRoute
One thing I see which is incorrect is that you are sending the adverse object in the function and then setting the param to the scope adverse.
The thing is that the $scope.adverse already holds the values so you don't need to pass the value and setting it to the scope again. Remeber the scope is your glue between the view and ctrl
$scope.editData = function(){
console.log($scope.adverse)
}

$auth.login is not a function

I'm using AngularJS 1.4.6 and Satellizer for oauth.
I'm doing everything as written but always get same error:
angular.js:12450 TypeError: $auth.login is not a function
login.html:
<div class="form-group">
<input type="email" class="form-control underline-input" placeholder="Email" ng-model="user.email" required>
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control underline-input" ng-model="user.password" required>
</div>
<div class="form-group text-left mt-20">
<button type="submit" class="btn btn-greensea b-0 br-2 mr-5" ng-click="login()" ng-disabled='form.$invalid'>Login</button>
<label class="checkbox checkbox-custom checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label>
<a ui-sref="core.forgotpass" class="pull-right mt-10">Forgot Password?</a>
</div>
</form>
Login controller:
.controller('LoginCtrl', function ($scope, $auth) {
$scope.user = {};
$scope.user.email = 'test#gmail.com';
$scope.user.password = 'test';
$scope.login = function () {
$auth.login($scope.user).then (
function (response) {
console.log(response);
},
function (error) {
console.log(error);
}
)
}
app.js:
.config(['$stateProvider', '$urlRouterProvider', '$authProvider', function($stateProvider, $urlRouterProvider, $authProvider ) {
$authProvider.loginUrl = '/auth/login';
...
I tried different settlements, researched github issues but not found a solution.
Whats my fault? How can I fix it?
I add to controller array option
.controller('LoginCtrl', ['$scope','$auth', function ($scope, $auth) {
$scope.user = {};
$scope.user.email = 'test#gmail.com';
$scope.user.password = 'test';
$scope.login = function () {
$auth.login($scope.user).then (
function (response) {
console.log(response);
},
function (error) {
console.log(error);
}
)
}]

$scope.data in controller function is undefined (ANGULARJS)

I have a function that creates a group by POSTing to an api but now im trying to get that function to append the newly created group to the users feed without the need of refreshing the page. I know i have to to do a .push and push the data to the array, but im having an issue where on .success(function(data) {} $scope.data comes back undefined so im unable to push the data to the $scope.feeds array. Any suggestions?
hello.controller('FeedListCtrl', ['$scope', '$http', '$window', '$cookies', '$modal', '$log', 'FeedService',
function FeedListCtrl($scope, $http, $window, $cookies, $modal, $log, FeedService, $modalInstance) {
$(function() {
$('.ns-notify').css("visibility", "visible");
$('body').css("padding", "40px 0");
});
$scope.feeds = [];
$scope.createGroupCall = function createGroupCall(teacher, name) {
$modalInstance.close();
FeedService.createGroupCall($cookies.token, $window.sessionStorage.user, teacher, name).success(function(data) {
console.log('GroupCreated');
console.log(data.name);
console.log(data.teacher);
console.log($scope.create);
console.log($scope.data + "THIS IS SCOPE.DATA");
console.log($scope.feeds + 'HEY!');
$scope.feeds.push($scope.data);
$scope.feedCall($cookies.token);
}).error (function(status,data,token) {
console.log(status);
console.log(data);
});
};
$scope.feedCall = function feedCall(token) {
FeedService.feedCall(token).success(function(data) {
$scope.feeds = data.results;
console.log("FEED Controller")
// console.log(data);
console.log(data.results);
console.log($scope.feeds);
}).error (function(status,data,token) {
console.log(status);
console.log(data);
});
}
$scope.feedCall($cookies.token);
}]);
<div>
<script type="text/ng-template" id="CreateGroupContent.html">
<div class="modal-header">
<h2 class="modal-title ns-modal-title">Create A Group</h2>
<button class="ns-modal-close" ng-click="cancel()"><img src="images/xCancel.png"></button>
</div>
<div class="modal-body">
<form class="form-signin" role="form">
<input type="text" class="form-control ns-modal-form" placeholder="Teacher" ng-model="create.teacher" required autofocus>
<input type="text" class="form-control ns-modal-form" placeholder="Group Name" ng-model="create.name" required>
<button class="btn btn-primary ns-modal-add" ng-click="createGroupCall(create.teacher, create.name);" type="submit">Create</button>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</script>
</div>
i am using bootstraps angular-ui plugin for my modals that should explain $modal, $modalInstance and $log
even though $scope.data is coming back undefined if i console.log(data) i actually get the data back.

Categories