Modify method to show success/failed Message. AngularJS - javascript

I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.
Heres the html code:
<form role="form">
<div class="panel-body">
<div class="panel-body">
<img src="/assets/doge.jpg" alt="Doge">
</div>
<div class="container">
<div class="input-group">
<span class="input-group-addon" id="tec-nombre">Nombre del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.nombre" aria-describedby="tec-nombre">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-legajo">Legajo del
Tecnico:</span><input type="number" class="form-control"
data-ng-model="tecnico.legajo" aria-describedby="tec-legajo">
<div role="alert">
<span class="error"
data-ng-show="myForm.legajoTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-email">Email del
Tecnico:</span><input type="email" class="form-control"
data-ng-model="tecnico.email" aria-describedby="tec-email">
<div role="alert">
<span class="error"
data-ng-show="myForm.emailTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-interno">Interno del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.interno" aria-describedby="tec-interno">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2"></label>
<div class="col-md-4">
Cancel
<a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary">Actualizar
{{tecnico.legajo}}</a>
<button data-ng-click="deleteCustomer(customer)"
data-ng-show="customer._id" class="btn btn-warning">Delete</button>
</div>
</div>
And heres the Angular Code:
angular.module('incidente', [ 'ngRoute' , 'ui.tree' ])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'partials/home.html'
}).when('/incidente/:codename', {
templateUrl : 'partials/incidente.html',
controller : 'IncidenteController'
}).when('/incidentes', {
templateUrl : 'partials/incidentes.html',
controller : 'IncidentesController'
}).when('/tecnicos', {
templateUrl : 'partials/tecnicos.html',
controller : 'TecnicosController'
}).when('/tecnico/:legajo', {
templateUrl : 'partials/tecnico.html',
controller : 'TecnicoController'
}).when('/sistema/:nombre', {
templateUrl : 'partials/sistema.html',
controller : 'SistemaController'
}).when('/sistemas', {
templateUrl : 'partials/sistemas.html',
controller : 'SistemasController'
}).when('/hardware/:codename', {
templateUrl : 'hardware.html',
controller : 'HardwareController'
}).when('/hardwares', {
templateUrl : 'partials/hardwares.html',
controller : 'HardwaresController'
}).when('/software/:codename', {
templateUrl : 'partials/software.html',
controller : 'SoftwareController'
}).when('/softwares', {
templateUrl : 'partials/softwares.html',
controller : 'SoftwaresController'
}).when('/readme', {
templateUrl : 'partials/readme.html',
controller : ''
}).when('/test', {
templateUrl : '/partials/tecnicos.html',
controller : 'TecnicosController'
}).otherwise({
redirectTo : '/'
});
} ])
.controller('home', function($scope, $http) {
$http.get('/resource/').success(function(data) {
$scope.greeting = data;
})
})
.controller(
'navigation',
function($rootScope, $scope, $http, $location) {
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/");
$scope.error = false;
} else {
$location.path("/login");
$scope.error = true;
}
});
};
})
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/" + code).then(
onIncidenteComplete, onError);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(urlbase + "set/incidente/" + incidente)
};
} ])
.controller(
'IncidentesController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onIncidenteComplete = function(response) {
try {
$scope.incidentes = angular
.fromJson(response.data);
console.log($scope.incidentes);
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/").then(
onIncidenteComplete, onError);
} ])
.controller(
'TecnicoController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var urlbase = "http://localhost:8080/";
var legajo = $routeParams.legajo;
var onTecnicoComplete = function(response) {
try {
$scope.tecnico = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/tecnico/" + legajo)
.then(onTecnicoComplete, onError);
$scope.saveTecnico = function(tecnico) {
return $http.post(urlbase + "set/tecnico/", tecnico)
};
This is the function that saves the tecnico and should show the error/success message.
} ])
.controller(
'TecnicosController',
[
'$scope',
'$http',
function($scope, $http) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
$http.get("http://localhost:8080/get/tecnico/")
.then(onTecnicoComplete, onError);
} ])
.controller(
'SistemasController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/get/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
$http.get(urlbase + "sistema/").then(
onSistemaComplete, onError);
} ]);
So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.

you could use
$scope.$on('$routeChangeStart', function(next, current) {
... you could trigger something here ...
});
and you should create a service that display something while changine route.
You have other events :
$routeChangeSuccess
$routeChangeError
$routeUpdate

Related

AngularJS Pass data to view

I have a controller that is as follows:
angular.module('myApp').controller('CoursesCtrl', function($scope, $auth, $location, toastr, Course, $http) {
$scope.selectedCourse = [];
$scope.getCourse = function(id){
Course.getCourse(id)
.then(function(response) {
$scope.selectedCourse = {
course_name : response.data.data['name'],
course_code : response.data.data['code']
}
$location.path('/course');
})
.catch(function(response) {
toastr.error(response.data.message, response.status);
});
};
});
With view as follows:
<div class="ten wide column" ng-controller="CoursesCtrl">
<h2 class="ui header">
{{selectedCourse.course_name}}
</h2>
<h4 class="ui header">
Instructor: {{selectedCourse.course_code}}
</h4>
</div>
I am unable to pass the data into the view which has the location path: course:
Looking closely in the code, is there something that has been left out or needs to be considered.
Because you have written code for selectedCourse in getCourse function so you have to write selectedCourse outside getCourse function.
angular.module('myApp').controller('CoursesCtrl', function($scope, $auth, $location, toastr, Course, $http) {
$scope.selectedCourse ={}; //here was the mistake
$scope.getCourse = function(id){
Course.getCourse(id)
.then(function(response) {
$scope.selectedCourse = {
course_name : response.data.data['name'],
course_code : response.data.data['code']
}
$location.path('/course');
})
.catch(function(response) {
toastr.error(response.data.message, response.status);
});
};
});
In your code $scope.selectedCourse is declared as array. declare it as an object for your purpose as $scope.selectedCourse = {};
angular.module('myApp').controller('CoursesCtrl', function ($scope, $auth, $location, toastr, Course, $http) {
//Loading the value based on the existance in parent controller.
$scope.selectedCourse = ($scope.$parent.selectedCourseData)? $scope.$parent.selectedCourseData: {};
$scope.getCourse = function (id) {
Course.getCourse(id)
.then(function (response) {
$scope.selectedCourse = {
course_name: response.data.data['name'],
course_code: response.data.data['code']
}
//Keeping the value in a parent controller
$scope.$parent.selectedCourseData = $scope.selectedCourse;
$location.path('/course');
})
.catch(function (response) {
toastr.error(response.data.message, response.status);
});
};
});

Angular: ng-repeat calculate data in view

I am writing an angular website, but I have the following problem. I have 2 data arrays that I get from my json files.
I use an ng-repeat to go over my projects in my html file, and I use another ng-repeat to go over my projects.languages.
Now what I want to do is to make it that for every language I find I am going to search in the languages data
and get the other information.
How can I easly get the language in the ng-repeat, I need to also calculate in that the data maybe not avaible yet,
because I get the json data async.
This is the code I have right now:
<div class="container-fluid contentcontainer">
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<div class="languageoverlay">
<span ng-repeat="language in projects[$index].languages">
<img ng-src="img/languages/android.png" ng-alt="{{language}}" />
<font ng-show="!$last">+</font>
</span>
</div>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
</div>
<!--this is just to try, don't need to use this-->
<h1>{{getLanguage("CSharp")}}</h1>
App.js
app.service('projectService', ['$http', '$q', function($http, $q) {
var projectsDeferred = $q.defer();
var languagesDeferred = $q.defer();
$http({
method: 'POST',
url: 'json/projects.json',
cache: true
}).then(function(data) {
projectsDeferred.resolve(data.data.projects);
});
$http({
method: 'POST',
url: 'json/projects.json',
cache: true
}).then(function(data) {
languagesDeferred.resolve(data.data.languages);
});
this.getProjects = function(){
return projectsDeferred.promise;
};
this.getLanguages = function(){
return languagesDeferred.promise;
};
}]);
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projects = {};
$scope.languages = {};
var promise = projectService.getProjects();
promise.then(function(data) {
$scope.projects = data;
});
var promise = projectService.getLanguages();
promise.then(function(data) {
$scope.languages = data;
});
// This was a try, don't need to use this
$scope.getLanguage = function(name) {
array.forEach(function(element) {
if (element.name == name) {
$scope.push(element);
}
}, $scope.languages);
};
}]);
languages.json
{
"result":"SUCCESS",
"resultMessage":"",
"languages":[
{
"name":"CSharp",
"FullName":"C#",
"img":"img/languages/csharp.png"
},
{
"name":"Android",
"FullName":"Android",
"img":"img/languages/android.png"
},
{
"name":"VisualStudio",
"FullName":"Visual Studio",
"img":"img/languages/visualstudio.png"
}
]
}
projects.json
{
"result":"SUCCESS",
"resultMessage":"",
"projects":[
{
"name":"Test1",
"img":"img/projects/photo-1453060113865-968cea1ad53a.jpg",
"languages":["Android"]
},
{
"name":"Test2",
"img":"img/projects/photo-1454165205744-3b78555e5572.jpg",
"languages":["Android"]
},
{
"name":"Test3",
"img":"img/projects/photo-1457305237443-44c3d5a30b89.jpg",
"languages":["CSharp","VisualStudio"]
},
{
"name":"Test4",
"img":"img/projects/photo-1457612928689-a1ab27da0dad.jpg",
"languages":["CSharp","VisualStudio"]
}
]
}
Easy piece:
First don't use $q just use $http
app.service('projectService', ['$http', '$filter', function($http, $filter) {
function callLanguages(languages) {
return $http({
method: 'GET',
url: 'json/projects.json',
cache: true
}).then(function (response) {
return buildProjectWithLanguages(response.data.projects, languages);
});
}
function buildProjectWithLanguages (projects, languages) {
return projects.map(function (p) {
var langs = p.languages.map(function (l) {
var matchLangs = $filter('filter')(languages, { name: l });
if (matchLangs.length) {
return matchLangs[0];
} else {
return { FullName: l };
}
});
p.languages = langs;
return p;
});
}
this.getProjects = function(){
return $http({
method: 'GET',
url: 'json/languages.json',
cache: true
}).then(function(response) {
return callLanguages(response.data.languages);
});
};
}]);
then simplify your controller
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projects = [];
projectService.getProjects(function (projects) {
$scope.projects = projects;
});
}]);
and finally change your html to this:
<div class="container-fluid contentcontainer">
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<div class="languageoverlay">
<span ng-repeat="language in project.languages">
<img ng-src="{{language.img}}" ng-alt="{{language.FullName}}" />
<font ng-show="!$last">+</font>
</span>
</div>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
</div>
I really loved your awnser, but I made another approach with directives. I tested your awnser and it looks like a correct awnser.
This is what I did:
projects-directive.html
<div class="row">
<div class="col-xs-6 col-md-3" ng-repeat="project in projects">
<a href="#/project/{{$index}}" class="thumbnail">
<img ng-src="{{project.img}}" ng-alt="{{project.name}}" />
<div class="caption">
<languages languagenames="project.languages"></languages>
<h3>{{project.name}}</h3>
</div>
</a>
</div>
</div>
languages-directive.html
<div class="languageoverlay">
<span ng-repeat="language in languages">
<img ng-src="{{language.img}}" ng-alt="{{language.FullName}}" />
<font ng-show="!$last">+</font>
</span>
</div>
app.js
app.service('projectService', ['$http', '$filter', function($http, $filter) {
this.getLanguages = function() {
return $http({
method: 'GET',
url: 'json/languages.json',
cache: true
});
}
this.getProjects = function(){
return $http({
method: 'GET',
url: 'json/projects.json',
cache: true
})
};
}]);
app.directive('projects', ['projectService', function(projectService) {
return {
restrict: 'E',
templateUrl: "directives/projects-directive.html",
scope: {
limitto: "=?"
},
controller: function($scope)
{
projectService.getProjects().then(function(response) {
projects = response.data.projects;
if (angular.isDefined($scope.limitto))
{
$scope.projects = projects.slice(0, $scope.limitto);
} else {
$scope.projects = projects;
}
});
}
}
}]);
app.directive('languages', ['projectService', '$filter', function(projectService, $filter) {
return {
restrict: 'E',
templateUrl: "directives/languages-directive.html",
scope: {
languagenames: "="
},
controller: function($scope)
{
projectService.getLanguages().then(function(response) {
$scope.languages = $scope.languagenames.map(function (l) {
var matchLangs = $filter('filter')(response.data.languages, { name: l });
if (matchLangs.length) {
return matchLangs[0];
} else {
return { FullName: l };
}
});
});
}
}
}]);
app.controller('PortfolioController', ['$scope', 'projectService', function($scope, projectService) {
$scope.projectlimit = 4;
}]);
app.controller('ProjectsController', ['$scope', 'projectService', function($scope, projectService) {
}]);
How to call the directive:
<projects></projects>
and if you want to limit it, you can add parameter:
<projects limitto="projectlimit"></projects>

$http.post from angular form not sending any data

I have a form that is posting /api/tradelink but it doesn't send any body or data with it.
HTML :
<form ng-submit="sendTradelink()">
<md-input-container class="md-accent">
<label>Enter your tradelink</label>
<input ng-model="tradelink">
</md-input-container>
<md-button type="submit" class="md-raised md-accent">Send</md-button>
</form>
Services :
.factory('Auth', ['$http', '$api', '$window', function ($http, $api, $window) {
var authFactory = {};
authFactory.authenticate = function(){
$http.post($api.url + 'auth')
.successs(function(url){
$window.location.href = url;
});
};
authFactory.send = function () {
return $http.post($api.url + 'tradelink');
};
return authFactory;
}]);
Controller ;
.controller('AppCtrl', ['$scope', 'Auth', '$location', '$cookies', function ($scope, Auth, $location, $cookies) {
var sidTemp = 'needtomakeitanewvalue';
$scope.checklogin = function () {
$scope.sid = $cookies.get('sid2');
console.log($scope.sid);
}
$scope.sendTradelink = function () {
Auth.send($scope.tradelink)
.success(function (res) {
$scope.sidTemp = 'needtomakeitanewvalue';
$cookies.put('sid2', sidTemp);
$location.path('/');
});
}
$scope.auth = function () {
Auth.authenticate();
}
}])
Server side holding api request, nothing inside req.body or req.params. Both show as empty objects.
api.post('/tradelink', function(req, res){
console.log(req.user.steamId);
console.log(req.params);
console.log(req.body);
res.json({
success: true,
message: 'tradelink received'
})
});
Check the Angular docs for $http.post
You are calling Auth.send($scope.tradelink), but your authFactory.send() function needs to accept this tradelink value and then be used as a data param to $http.post()
So:
authFactory.send = function (tradelink) {
return $http.post($api.url + 'tradelink', {tradelinkId: tradelink });
};

Token-Based Authentication With AngularJS & NodeJS

So, I came up from this Token-Based Authentication With AngularJS & NodeJS tutorial.
Now I want to implement my own RESTful Api to my AngularJS. Here it is my RESTful Api: http://amr2.mybluemix.net/getpop/list
The response from JSON is like this:
[
{
"_id": "fe107409a330778c0e22ebd8e34ca8fd",
"_rev": "2-292360cf343367741469397112ff9a82",
"d": {
"parentsite": "1",
"siteID": "10001",
"location": "",
"domain": "#test",
"users": {
"0": {
"user": "admin#test",
"pass": "12345",
"level": 0
},
"1": {
"user": "view#test",
"pass": "12345",
"level": 1
}
},
"readpoint": {
"0": {
"uSN": "100010001",
"metername": "demokit",
"activedate": ""
},
"1": {
"uSN": "100010002",
"metername": "demokit2",
"activedate": ""
}
}
}
}
]
I want to authenticate whether it is admin#test or view#test whose login to my angular.
This is <body> in my index.html
<body ng-app="angularRestfulAuth">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation" data-ng-controller="HomeCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Angular Restful Auth</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a ng-href="#/">Home</a></li>
<li data-ng-show="token"><a ng-href="#/me">Me</a></li>
<li data-ng-hide="token"><a ng-href="#/signin">Signin</a></li>
<li data-ng-hide="token"><a ng-href="#/signup">Signup</a></li>
<li data-ng-show="token"><a ng-click="logout()">Logout</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" ng-view="">
</div> <!-- /container -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>
<script src="/lib/ngStorage.js"></script>
<script src="/lib/loading-bar.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controllers.js"></script>
<script src="/scripts/services.js"></script>
</body>
This is services.js
'use strict';
angular.module('angularRestfulAuth')
.factory('Main', ['$http', '$localStorage', function($http, $localStorage){
var baseUrl = "https://amr2.mybluemix.net/getpop/list";
function changeUser(user) {
angular.extend(currentUser, user);
}
function urlBase64Decode(str) {
var output = str.replace('-', '+').replace('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
return window.atob(output);
}
function getUserFromToken() {
var token = $localStorage.token;
var user = {};
if (typeof token !== 'undefined') {
var encoded = token.split('.')[1];
user = JSON.parse(urlBase64Decode(encoded));
}
return user;
}
var currentUser = getUserFromToken();
return {
save: function(data, success, error) {
$http.post(baseUrl + '/signin', data).success(success).error(error)
},
signin: function(data, success, error) {
$http.post(baseUrl + '/authenticate', data).success(success).error(error)
},
me: function(success, error) {
$http.get(baseUrl + '/me').success(success).error(error)
},
logout: function(success) {
changeUser({});
delete $localStorage.token;
success();
}
};
}
]);
This is controller.js
'use strict';
angular.module('angularRestfulAuth')
.controller('HomeCtrl', ['$rootScope', '$scope', '$location', '$localStorage', 'Main', function($rootScope, $scope, $location, $localStorage, Main) {
$scope.signin = function() {
var formData = {
email: $scope.email,
password: $scope.password
}
Main.signin(formData, function(res) {
if (res.type == false) {
alert(res.data)
} else {
$localStorage.token = res.data.token;
window.location = "/";
}
}, function() {
$rootScope.error = 'Failed to signin';
})
};
$scope.signup = function() {
var formData = {
email: $scope.email,
password: $scope.password
}
Main.save(formData, function(res) {
if (res.type == false) {
alert(res.data)
} else {
$localStorage.token = res.data.token;
window.location = "/"
}
}, function() {
$rootScope.error = 'Failed to signup';
})
};
$scope.me = function() {
Main.me(function(res) {
$scope.myDetails = res;
}, function() {
$rootScope.error = 'Failed to fetch details';
})
};
$scope.logout = function() {
Main.logout(function() {
window.location = "/"
}, function() {
alert("Failed to logout!");
});
};
$scope.token = $localStorage.token;
}])
.controller('MeCtrl', ['$rootScope', '$scope', '$location', 'Main', function($rootScope, $scope, $location, Main) {
Main.me(function(res) {
$scope.myDetails = res;
}, function() {
$rootScope.error = 'Failed to fetch details';
})
}]);
This is app.js
'use strict';
angular.module('angularRestfulAuth', [
'ngStorage',
'ngRoute',
'angular-loading-bar'
])
.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}).
when('/signin', {
templateUrl: 'partials/signin.html',
controller: 'HomeCtrl'
}).
when('/signup', {
templateUrl: 'partials/signup.html',
controller: 'HomeCtrl'
}).
when('/me', {
templateUrl: 'partials/me.html',
controller: 'HomeCtrl'
}).
otherwise({
redirectTo: '/'
});
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/signin');
}
return $q.reject(response);
}
};
}]);
}
]);
Can anybody show me what i have been missing and how to fix it?

Binding data to AngularUI dialog

I'm trying to write a simple angularapp to allow the teachers to edit their class information. I'm using angular-ui dialog directive to get the lightbox. On userclick I've written a function to pass the data to the modal and open the dialog. But for some reason the data is not properly binded.
This is my controller.js
'use strict';
define(['app' ], function(app) {
app.controller('TeacherClasses',
[ '$scope', '$http', '$dialog','$location', 'teacherClassService',
function($scope, $http, $dialog, $location, teacherClassService) {
$scope.newClass={};
$scope.show = {"createClassModal": false};
$http.get('/grades').success(function(data) {
$scope.grades = data;
});
$scope.newClass.grade = "Grade";
$scope.setGrade = function(grade){
$scope.newClass.grade = grade;
};
$scope.fetchStudentGroups = function(){
$http.get('/teacher/studentGroups').success(function(data) {
$scope.studentGroups = data;
});
};
$scope.fetchStudentGroups();
$scope.createClass = function(){
$http.post('/studentGroup', $scope.newClass).
success(function(data, status, headers, config) {
$scope.show.createClassModal = false;
//Clearing it out for next time
$scope.newClass = {};
$scope.fetchStudentGroups();
}).
error(function(data, status, headers, config) {
});
console.log($scope.newClass);
};
$scope.openDialog = function(studentGroup, dialog){
$scope.newClass = angular.copy(studentGroup);
$scope.opts = {
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '/assets/partials/teacher/manage/editClassInfo.html',
resolve: {
data: function(){
return $scope.newClass;
}
}
};
var modal = $dialog.dialog($scope.opts);
modal.open();
}
}]);
return app;
});
And this is my partial
<div class="modal-header">
Edit Class
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<input type="text" ng-model="newClass.name" class="span4">
</div>
<div class="control-group">
<select ui-select2 data-placeholder="Choose a grade" id="grades" class="span4">
<option></option>
<option ng-repeat="grade in grades" ng-model="grades" >{{grade}}</option>
</select>
</div>
<label>Students {{newClass.noOfStudents}}</label>
<label>{{newClass.name}}</label>
</form>
</div>
<div class="modal-footer"></div>
My module definitions are in app.js
'use strict';
define([ 'angular' ], function(angular) {
var myModule = angular.module('myApp',
[ 'ngResource', 'ui', 'infinite-scroll', 'ngDragDrop', 'blueimp.fileupload','ui.bootstrap.dialog', 'ui.bootstrap.modal',
'ui.bootstrap.dropdownToggle', 'LoadingIndicator', 'http-auth-interceptor']);
myModule.value('ui.config', {
select2 : {
allowClear : true
},
redactor: {
plugins: ['fullscreen']
}
});
return myModule;
});
But none of these values are tied back to the view. What am I doing wrong here?

Categories

Resources