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.
Related
So, I am creating a web app, where one page I have a user list and on the second page, I have the users details page. On the second page, I have a confirm button where I want to remove that user when the "Confirm" button is clicked with a 200 Status code. However, I am getting a DELETE : 405 (Method Not Allowed). So, here is my code down below. Please tell me or help me fix this problem. Thank you in advance.
Here is my code.
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<button class="btn btn-primary" ng-click="doDelete(id)">Confirm</button>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
</fieldset>
</form>
</div>
</div>
</div>
Services
app.factory('people', function ($http) {
var service = {};
service.getUserInfo = function () {
return $http.get('https://api-dev.mysite.io/admin/v1/unconfirmed_lawyers');
};
service.confirmUser = function (lawyerId) {
return $http.put('https://api-dev.mysite.io/admin/v1/lawyers/{lawyerId}/confirm');
};
return service;
});
LawyerController
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
$scope.lawyerId = $routeParams.id;
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
});
}]);
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
}, function (error) {
console.log(error)
});
}
});
App.js
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1);
location.href = '#/lawyer';
};
If you changed your HTML, so you passed the person instead.
<button class="btn btn-primary" ng-click="doDelete(person)">Confirm</button>
You can use this to find the index within the lawyers, then remove it.
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1)
};
The issue is your are using $http.delete which performs an HTTP Delete request. This doesn't sound like something you intended.
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)
}
In my angular controller, I am trying to save a token when returned from an API end point which is returned as a string. For this example, I've replaced it with the variable testData.
var testData = "testdata"
$localStorage['jwtToken'] = testData
localStorage.setItem('jwtToken',testData)
For the first line, this is what is stored:
{"ngStorage-jwtToken" : ""testdata""}
First the second line:
{"jwtToken" : "testdata"}
I understand why the key is changing but what I don't understand is why there is a double "" around the data string stored in the value of the key by the first line.
Has anyone come across this before? Am I doing anything wrong?
Best efforts to add the code below.
angular.module('app', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngSanitize',
'ngTouch',
'ngStorage',
'ui.router'
]);
app.controller('SigninFormController', ['$scope', '$http', '$state', '$localStorage',
function($scope, $http, $state, $localStorage) {
$scope.user = {};
$scope.authError = null;
$scope.login = function() {
$scope.authError = null;
// Try to login
$http.post('api/auth/login', {
email: $scope.user.email,
password: $scope.user.password
})
.then(function(response) {
if (response.status = 200 && response.data.token) {
var testData = "testdata"
$localStorage['jwtToken'] = testData
localStorage.setItem('jwtToken', testData)
/*
$localStorage['jwtToken'] = response.data.token
localStorage.setItem('jwtToken',response.data.token)
*/
$state.go('app.home');
} else {
$scope.authError.message
}
}, function(err) {
if (err.status == 401) {
$scope.authError = err.data.message
} else {
$scope.authError = 'Server Error';
}
});
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<body ng-controller="">
<div class="container w-xxl w-auto-xs" ng-controller="SigninFormController">
<div class="m-b-lg">
<div class="wrapper text-center">
<strong>Sign in to get in touch</strong>
</div>
<form name="form" class="form-validation">
<div class="text-danger wrapper text-center" ng-show="authError">
{{authError}}
</div>
<div class="list-group list-group-sm">
<div class="list-group-item">
<input type="email" placeholder="Email" class="form-control no-border" ng-model="user.email" required>
</div>
<div class="list-group-item">
<input type="password" placeholder="Password" class="form-control no-border" ng-model="user.password" required>
</div>
</div>
<button type="submit" class="btn btn-lg btn-primary btn-block" ng-click="login()" ng-disabled='form.$invalid'>Log in</button>
<div class="text-center m-t m-b"><a ui-sref="access.forgotpwd">Forgot password?</a></div>
<div class="line line-dashed"></div>
<p class="text-center"><small>Do not have an account?</small></p>
<a ui-sref="access.signup" class="btn btn-lg btn-default btn-block">Create an account</a>
</form>
</div>
<div class="text-center" ng-include="'tpl/blocks/page_footer.html'">
</div>
</div>
</body>
Why the double quotes
I would need to look at the source code, but most likely the reason why they put quotes around the string is so they can use JSON.parse() so and get the correct object/array/string out of the storage without having to try to figure out the types.
Basic idea:
localStorage.setItem('xxx', '"testData"');
var val1 = JSON.parse(localStorage.getItem('xxx'));
localStorage.setItem('yyy', '"testData"');
var val2 = JSON.parse(localStorage.getItem('{"foo" : "bar"}'));
Why do they prepend the key name?
They can loop over the keys and know what localstorage keys are angulars and what ones are something else. They they can populate their object.
var myStorage = {};
Object.keys(localStorage).forEach(function(key){
if (key.indexOf("ngStorage")===0) {
myStorage[key.substr(10)] = JSON.parse(localStorage[key]);
}
});
I have a master controller and I would like to set up the login page to take me to "/tables" path if username=admin and password=admin, however I am getting this error everytime I try to login
TypeError: Cannot read property 'path' of undefined
I added $location in the controller and in the login function but nothing changed keep getting same error. If I take $location out I get this error
ReferenceError: $location is not defined
Not sure what to do there. Any help is appreciated. Here is my code
angular
.module('RDash')
.controller('MasterCtrl', ['$scope', '$cookieStore', MasterCtrl]);
function MasterCtrl($scope, $cookieStore, $location) {
/**
* Sidebar Toggle & Cookie Control
*/
var mobileView = 992;
$scope.getWidth = function() {
return window.innerWidth;
};
$scope.login = function($location) {
if($scope.credentials.username !== "admin" && $scope.credentials.password !== "admin") {
alert("you are not the admin");
}
else{
$location.path('/tables');
}
};
}
login.html:
<div ng-controller="MasterCtrl">
<form >
<div class="jumbotron" class="loginForm">
<div class="form-group" id="loginPageInput">
<label for="exampleInputEmail1">User Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Username" ng-model="credentials.username">
</div>
<div class="form-group" id="loginPageInput">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" ng-model="credentials.password">
</div>
<div id="loginPageInput">
<button ng-click="login()" type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
</form>
<div id="loginPageInput">
<div class="wrap">
<button ng-click="register()" class="btn btn-default" id="lefty" >Register</button>
<p ng-click="forgotpass()" id="clear"><a>Forgot my Password</a></p>
</div>
</div>
</div>
</div>
You missed to inject $location in your dependency array of MasterCtrl
Code
angular
.module('RDash')
.controller('MasterCtrl', ['$scope', '$cookieStore', '$location', MasterCtrl]);
//^^^^^^^^
function MasterCtrl($scope, $cookieStore, $location) {
Also you need to remove $scope.login parameter $location which is killing the service $location variable existance which is inject from the controller.
$scope.login = function ()
You are not passing any $location to login function hence it's undefined and shadows outer $location local variable. Correct code should be:
$scope.login = function () {
if ($scope.credentials.username !== "admin" && $scope.credentials.password !== "admin") {
alert("you are not the admin");
} else {
$location.path('/tables');
}
};
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.