I am trying to route my navbar using angular js but the content in that HTML file is not displaying, I don't know what is the problem.
here is my register page in this register and login functionality is there on angularjs parse
<!DOCTYPE html>
<html ng-app="AuthApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<!-- start: CSS -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript" src="js/signuplogintoggle.js" charset="utf-8"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link href="css/style.css" rel="stylesheet">
<link href="css/sidebarnav.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-ext' rel='stylesheet' type='text/css'>
<!-- end: CSS -->
<meta charset=utf-8 />
<title>EPPF</title>
</head>
<body>
<div class="main-container">
<div ng-hide="currentUser">
<form ng-show="scenario == 'Sign up'" class="form-signin" role="form">
<h2 class="form-signin-heading text-center">EPPF</h2>
Email: <input type="email" ng-model="user.email" class="form-control" /><br />
Username: <input type="text" ng-model="user.username" class="form-control" /><br />
Password: <input type="password" ng-model="user.password" class="form-control"/><br />
<button ng-click="signUp(user)" class="btn btn-lg btn-primary btn-block">Sign up</button>
</br>
Login</p>
</div>
</form>
<form ng-show="scenario == 'Log in'" class="form-signin" role="form">
<h2 class="form-signin-heading">Please sign in</h2>
Username: <input type="text" ng-model="user.username" class="form-control" role="form"/><br />
Password: <input type="password" ng-model="user.password" class="form-control" role="form" /><br />
<button ng-click="logIn(user)" class="btn btn-lg btn-primary btn-block">Log in</button>
</br>
Sign up</p>
</form>
</div>
<div ng-show="currentUser">
<div id="wrapper">
<div class="" ng-controller = "MainCtrl">
<div class="container">
<div class="menu">
<a ng-click="setRoute('home')" class="btn">Home</a>
<a ng-click="setRoute('about')" class="btn" >About</a>
<a ng-click="setRoute('dashboard')" class="btn">dashboard</a>
</div>
<div class="ng-view">
</div>
</div>
</div>
<button ng-click="logOut(user)" class="logout">Log out</button>
</div>
<script type="text/javascript">
Parse.initialize("34olOarYIJtsSy1YcuCdR4RFBPzKthQfAyotWjXP", "vvoqLVt7kMDwuxYliMuOJthEpMvRA3PVFdxC5izY");
angular.module('AuthApp', [])
.run(['$rootScope', function($scope) {
$scope.scenario = 'Sign up';
$scope.currentUser = Parse.User.current();
$scope.signUp = function(form) {
var user = new Parse.User();
user.set("email", form.email);
user.set("username", form.username);
user.set("password", form.password);
user.signUp(null, {
success: function(user) {
$scope.currentUser = user;
$scope.$apply();
},
error: function(user, error) {
alert("Unable to sign up: " + error.code + " " + error.message);
}
});
};
$scope.logIn = function(form) {
Parse.User.logIn(form.username, form.password, {
success: function(user) {
$scope.currentUser = user;
$scope.$apply();
},
error: function(user, error) {
alert("Unable to log in: " + error.code + " " + error.message);
}
});
};
$scope.logOut = function(form) {
Parse.User.logOut();
$scope.currentUser = null;
};
}]);
</script>
</body>
</html>
This is my register page and angular js code is
angular.module('AuthApp',[]).
config(function($routeProvider){
$routeProvider.
when('/about', {template:'partials/about.html'}).
when('/dashboard', {template:'partials/dashboard.html'}).
otherwise({redirectTo:'/home',template:'partials/home.html'})
});
function MainCtrl($scope,$location) {
$scope.setRoute = function(route){
$location.path(route);
}
}
I don't know what is the problem I cannot see the routes in ngview directory
I think the ngRoute service is missing there :
angular.module('AuthApp', ['ngRoute']);
See the doc : https://docs.angularjs.org/api/ngRoute
Also, it's suppose to be templateUrl instead of template.
angular.module('AuthApp',['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/about', {templateUrl:'partials/about.html'})
.when('/dashboard', {templateUrl:'partials/dashboard.html'})
.otherwise({redirectTo:'/home',templateUrl:'partials/home.html'})
});
function MainCtrl($scope,$location) {
$scope.setRoute = function(route){
$location.path(route);
}
}
Also, I don't think you should use the setRoute function. You should just set the href like that :
Home
Related
I am having this issue with my home button not adding headers in a get request. I have stored a token inside of the localStorage and I send it in the headers when I make a get request to Controller: Home Action: Index. From what I see, it doesn't use my jquery and goes straight to the Account/Index.
Initially, I though it was a problem with the javascript not binding to a button click. After further investigation, I found that the Console.log() I have in _Layout.cshtml do not work and neither does the button. This leads me to believe there is a problem with $("html").html(response); in the Login.js file.
The correct flow is LoginPage -> Login.js (grabs data and uses Ajax for a post request.) -> Returns a html page composing of _Layout.cshtml and /Views/Home/Index.cshtml
Below is my code for the file "Views/Shared/_Layout.cshtml":
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - Chat </title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" 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>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="li_btnHome"><a asp-area="" asp-controller="" asp-action="">Home</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© 2018 - Chat</p>
</footer>
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script type="text/javascript">
console.log("Development");
</script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
<script type="text/javascript">
console.log("Not Development");
</script>
</environment>
<script type="text/javascript">
console.log("Hello World");
</script>
<!--<script src="~/js/NavBarFunction.js"></script>-->
#RenderSection("Scripts", required: false)
</body>
</html>
Here's the javascript file "wwwroot/js/NavBarFunctions.js":
$("#li_btnHome a")[0].onclick = function (event) {
event.preventDefault();
alert("called click");
var tokenObj = localStorage.getItem("token");
var tokenStr = tokenObj == null ? "what_about_tokenObj_is_null?" : tokenObj.toString();
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: '#Url.Action("Index", "Home")',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", tokenStr);
},
success: function (response) {
alert(1);
$("html").html(response);
}
});
return false;
};
Here's the HomeController, located in "Controllers/HomeController":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Chat.Enums;
using Chat.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
namespace _Chat.Controllers
{
public class HomeController : Controller
{
private AuthenticateUser authenticateUser = new AuthenticateUser();
public async Task<IActionResult> Index()
{
var request = Request;
var headers = request.Headers;
StringValues token;
if (headers.TryGetValue("Authorization", out token))
{
var result = await this.authenticateUser.ValidateToken(token);
if (result.Result == AuthenticateResult.Success)
{
return View();
}
else
{
return RedirectToAction("Index", "Account");
}
}
return RedirectToAction("Index", "Account");
}
}
}
For some odd reason, it looks like after my page is redirected from log in to home, all scripts/javascript stop working.
Here's the code authenticating login. Located in "Controllers/AccountController":
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Chat.Models;
using Chat.DatabaseAccessObject;
using Chat.Identity;
using Chat.DatabaseAccessObject.CommandObjects;
using System.Linq.Expressions;
using System.Net.Mime;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.IdentityModel.Tokens;
namespace Chat.Controllers
{
public class AccountController : Controller
{
private const string SECRET_KEY = "CHATSECRETKEY";
public static SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
private ServerToStorageFacade serverToStorageFacade = new ServerToStorageFacade();
private AuthenticateUser authenticateUser = new AuthenticateUser();
public IActionResult Index()
{
return View();
}
// Post: /login/
[HttpPost]
public async Task<IActionResult> Login([FromBody]LoginModel loginModel)
{
if (ModelState.IsValid)
{
var mapLoginModelToUser = new MapLoginModelToUser();
var user = await mapLoginModelToUser.MapObject(loginModel);
// If login user with those credentials does not exist
if(user == null)
{
return BadRequest();
}
else
{
var result = await this.authenticateUser.Authenticate(user);
if(result.Result == Chat.Enums.AuthenticateResult.Success)
{
// SUCCESSFUL LOGIN
// Creating and storing cookies
var token = Json(new
{
data = this.GenerateToken(user.Email, user.PantherID),
redirectUrl = Url.Action("Index","Home"),
success = true
});
return Ok(token);
}
else
{
// Unsuccessful login
return Unauthorized();
}
}
}
return BadRequest();
}
private string GenerateToken(string email, string pantherId)
{
var claimsData = new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Actor, pantherId) };
var signInCredentials = new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "localhost",
audience: "localhost",
expires: DateTime.Now.AddDays(7),
claims: claimsData,
signingCredentials: signInCredentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public class MapLoginModelToUser
{
private ServerToStorageFacade serverToStorageFacade;
public MapLoginModelToUser()
{
serverToStorageFacade = new ServerToStorageFacade();
}
public async Task<User> MapObject(LoginModel loginModel)
{
Expression<Func<User, bool>> expression = x => x.Email == loginModel.inputEmail;
var user = await this.serverToStorageFacade.ReadObjectByExpression(new User(Guid.NewGuid()), expression);
if(user == default(Command))
{
return null;
}
return new User(user.ID)
{
Email = loginModel.inputEmail,
Password = loginModel.inputPassword,
FirstName = user.FirstName,
LastName = user.LastName,
PantherID = user.PantherID,
ClassDictionary = user.ClassDictionary,
UserEntitlement = user.UserEntitlement
};
}
}
}
Also the code that renders the page. Located in "wwwroot/js/Login.js":
$(document).ready(function () {
$("#formSubmit").submit(function (event) {
event.preventDefault();
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
var remember = $("#rememberMe").val();
var loginModel = {
inputEmail: email,
inputPassword: password,
rememberMe: remember
};
$.ajax({
type: 'POST',
url: 'Account/Login',
data: JSON.stringify(loginModel),
contentType: 'application/json; charset=utf-8;',
success: function (response) {
var token = response.value.data;
localStorage.setItem("token", token);
alert("You have successfully logged in.");
setHeader();
redirect(response.value.redirectUrl);
}
});
});
function setHeader() {
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', localStorage.getItem("token"));
}
});
}
function redirect(redirectUrl) {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: redirectUrl,
success: function (response) {
$("html").html(response);
}
});
}
});
This is the error received after loading the new html page:
EDIT: This is what's sent in the response after the Home button is clicked.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login - Chat FIU</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="/css/site.css" />
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" 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>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a id="btnHome" href="/">Home</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="/css/signin.css" rel="stylesheet">
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/Login.js"></script>
</head>
<body class="text-center">
<form id="formSubmit" method="post" class="form-signin">
<img class="mb-4" src="/images/FIU-Chat-Curved.png" alt="" width="150" height="150">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputEmail" class="sr-only">Email address</label>
<input autofocus="" class="form-control" data-val="true" data-val-required="The Email field is required." id="inputEmail" name="inputEmail" placeholder="Email address" required="required" type="email" value="" />
<label for="inputPassword" class="sr-only">Password</label>
<input class="form-control" data-val="true" data-val-required="The Password field is required." id="inputPassword" name="inputPassword" placeholder="Password" required="required" type="password" />
<div class="checkbox mb-3">
<label>
<input data-val="true" data-val-required="The Remember field is required." id="rememberMe" name="rememberMe" type="checkbox" value="true" /> Remember me
</label>
</div>
<button id="btnLogin" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Ah5tOyN_3lPrH0DgSEU8vD7Q7JItdizW-mYDc5uamCO3oRTBN-pdo9ZyPgRaHRyovwEGfT5Qhw0UD-rfbIHUJPt4FgUOhM1OkAWC9AtAfPEKkxz7TBfwKfz0EpfxF4DX2DAczujogr__xnIr3vDq3o" /><input name="rememberMe" type="hidden" value="false" /></form>
</body>
</html>
<hr />
<footer>
<p>© 2018 - Chat FIU</p>
</footer>
</div>
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=BxFAw9RUJ1E4NycpKEjCNDeoSvr4RPHixdBq5wDnkeY"></script>
<script type="text/javascript">
</script>
<script type="text/javascript">
</script>
<script src="/js/NavBarFunction.js"></script>
</body>
The key to solve the problem is in your flow described here:
The correct flow is LoginPage -> Login.js (grabs data and uses Ajax
for a post request.) -> Returns a html page composing of
_Layout.cshtml and /Views/Home/Index.cshtml
This kind of flow implies that you want to redirect into index page (proved by usage of return RedirectToAction("Index", "Account"); in controller action), which AJAX usage in redirection with GET method makes no sense (because AJAX call intended to stay in the same page).
Instead of replacing entire HTML page content using $("html").html(response);, use window.location.href to redirect with specified URL like this:
NavBarFunctions.js
$("#li_btnHome a")[0].click(function (event) {
event.preventDefault();
alert("called click");
var tokenObj = localStorage.getItem("token");
var tokenStr = tokenObj == null ? "what_about_tokenObj_is_null?" : tokenObj.toString();
$.ajax({
type: 'GET',
url: '#Url.Action("Index", "Home")',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", tokenStr);
},
success: function (response) {
// this is just an example, replace action & controller name as you wish
window.location.href = '#Url.Action("ActionName", "ControllerName")';
}
});
});
Login.js
function redirect(redirectUrl) {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: redirectUrl,
success: function (response) {
window.location.href = redirectUrl;
}
});
}
However if you want to render certain portion of the page using partial view, you may use jQuery.html() targeting a placeholder, e.g. <div> tag:
<!-- partial view placeholder -->
<div id="content">...</div>
// ajax callback
$.ajax({
// other settings
.....
success: function (response) {
$('#content').html(response);
},
.....
});
I am trying to add userName use AngularJs into Sharepoint. Also, i should have a feature that I should view all the userName from SharePoint list. But i keeping getting error says '_spPageContextInfo is not defined'.
I am start learning SharePoint and AngularJs. Can someone help me with it? Thank you.
Here is the code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<!-- modules -->
<script src="app.js"></script>
<!-- controllers -->
<script src="view.js"></script>
<script src="add.js"></script>
</head>
<body ng-app="myApp">
<h3>view</h3>
<div class="view" ng-controller="viewItemsController" ng-repeat="user in users">
<!-- {{user.ID}}: -->
{{user.Title}}, {{user.FirstName}},{{user.LastName}}
<br />
</div>
<hr>
<h3>add</h3>
<div class="add" ng-controller="addItemsController">
<div class="Table">
<div class="Row">
<div class="Cell">Title :</div>
<div class="Cell">
<input type="text" id="title" ng-model="title" />
</div>
</div>
<div class="Row">
<div class="Cell">First Name :</div>
<div class="Cell">
<input type="text" id="firstName" ng-model="firstName" />
</div>
</div>
<div class="Row">
<div class="Cell">Last Name :</div>
<div class="Cell">
<input type="text" id="lastName" ng-model="lastName" />
</div>
</div>
<div class="Row">
<div class="Cell"></div>
<div class="Cell">
<input type="button" id="btnAddContact" value="Add Name" ng-click="addContact()" />
</div>
</div>
</div>
</div>
</body>
</html>
app.js //this is module
var spApp = angular.module('myApp',[]);
view.js // first controller
spApp.controller("viewItemsController", function ($scope, $http) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Users')/items?$select=Title,First_Name,Last_Name";
$http(
{
method: "GET",
url: url,
headers: { "accept": "application/json;odata=verbose" }
}
).success(function (data, status, headers, config) {
console.log(data);
$scope.users = data.d.results;
}).error(function (data, status, headers, config) {
});
});
add.js // second controller
spApp.controller("addItemsController",function($scope,$http){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Users')/items";
var vm = $scope;
vm.addContact = function () {
return $http({
headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": jQuery("#__REQUESTDIGEST").val() },
method: "POST",
url: url,
data: {
'Title': vm.title,
'First_Name': vm.firstName,
'Last_Name':vm.lastName
}
})
.then(saveContact)
.catch(function (message) {
console.log("addContact() error: " + message);
});
function saveContact(data, status, headers, config) {
alert("User Added Successfully");
return data.data.d;
}
}
});
I go through your code, you have made spelling mistake with the script tag
If you see your Html code which you have added into your question
<!-- controllers -->
<sript src="view.js"></script>
<sript src="add.js"></script>
I have test your code on my system by correcting the spelling mistake as bellow and its working.
<!-- controllers -->
<script src="view.js"></script>
<script src="add.js"></script>
Hope so this will help you.
This is my controller from which I am requesting to POST the data on server. While I am able to POST title and rating, i am unable to POST any genres because Genres is an array. How to push the data in Genres Array?
app.controller('addTrack', function ($scope, $http) {
$scope.tracks = [];
var genre = [];
var pushing = genre.push($scope.add_genre);
$scope.add_track = "";
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.tracks = response.data.results;
});
$scope.add = function (event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', {
title: $scope.add_title,
rating: $scope.add_rating,
})
.then(function (data) {
$scope.genres = data;
//console.log($scope.add_genre);
$scope.add_title = '';
$scope.add_rating = '';
$scope.add_genre = '';
});
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.genres = response.data.results;
});
}
} });
Http POST to http://104.197.128.152:8000/v1/tracks
Accepted response
{
"title": "animals",
"rating": 4.5,
"genres": [
1
]
}
Providing you my HTML as well.
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="add_title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="add_genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="add_rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
<div class="clearfix">
<label>Available Tracks</label>
<ul class="list-group" ng-repeat="track in tracks">
<li class="list-group-item clearfix"><span class="pull-left title">{{track.title}}</span> <span class="genre">[{{track.genres[0].name}}]</span> <span class="pull-right rating">{{track.rating}}</span></li>
</ul>
</div>
</div>
</body>
</html>
If what you are trying to achieve is to add a track object with title, rating and genre, you need to change your whole logic so your controller will bind all inputs to the same object properties.
First you need to define a track object in your controller, and bind the inputs to its properties in your HTML:
JavaScript:
app.controller('addTrack', function($scope, $http) {
$scope.tracks = [];
$scope.track = {
title: '',
rating: 0,
genre: ''
};
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function(response) {
$scope.tracks = response.data.results;
});
$scope.add = function(event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', $scope.track)
.then(function(data) {
$scope.track = {};
});
}
}
});
HTML:
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="track.title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="track.genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="track.rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
</div>
</body>
</html>
Note:
Note the use of ng-model="track.title", ng-model="track.rating"
and ng-model="track.genre" in the HTML to bind these inputs to our
trackobject properties.
This code assumes that genre will be a string here, if you will use a
list of object you need to amend your code so it fits this option.
INDEX.HTML
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.0/ui-bootstrap-tpls.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="module in validation.modules">Title:{{module.title}}
description:{{module.description}}</div>
<div>
<form name="myForm" novalidate class="simple-form">
Title: <input value="" type="text" placeholder="a" ng-model="itemAmount"><br />
description: <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
<br />
<button ng-click="addItem()">Add to list</button>
</form>
</div>
</body>
</html>
APP.JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.validation = {
"modules":
[
{
"title":"name of validation1",
"description":"description of validation1"
},
{
"title":"name of validation2",
"description":"description of validation2"
}
]
};
$scope.addItem = function () {
$scope.validation.modules.push({
title: $scope.itemAmount,
description: $scope.itemName
});
};
});
The below file is a pluknr in which i am just binding using ng-model to display
http://plnkr.co/edit/5NXHQiOApzNU5cn0yQT2
My Question is that you can see in the plunker file that there is a add to list button .. what i want to do is that i want to add a pop up tab like the one you can see in the MODAL section in the below link
https://angular-ui.github.io/bootstrap/
and add some text fields to it let's suppose a form and when i click add to list in the pop up form i want it to be added in the view..
Here you go
http://plnkr.co/edit/nI6PhjbAKEdTgXeWMKDx?p=preview
Opening the modal in main controller and handling the result from modal:
$scope.openModal = function() {
var modalInstance = $modal.open({
templateUrl : 'myModal.html',
controller: 'myModalController'
})
modalInstance.result.then(function(info) {
console.log(info);
$scope.validation.modules.push(info);
})
Binding data into modal controller:
app.controller('myModalController', function($scope, $modalInstance) {
$scope.infoToAdd = {
title: "",
description: ""
}
$scope.addItem = function() {
$modalInstance.close($scope.infoToAdd);
}
$scope.cancel = function() {
$modalInstance.dismiss("cancel");
}
});
Template:
<script type="text/ng-template" id="myModal.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
Title: <input type="text" placeholder="Title" ng-model="infoToAdd.title"><br />
description: <input type="text" placeholder="Description" ng-model="infoToAdd.description">
<br />
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="addItem()">Add to list</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
hi I was trying to do a log-in form in angular but i don't know where to start, any help or maybe reference would be appreciated
i tried to type a function that checks username and pass but i can't redirect it to another page
any help please?????????????
here is my html code
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app="loginform">
<ion-pane ng-controller="AppCtrl">
<ion-header-bar class="bar-stable">
<h1 class="title">Unilever</h1>
</ion-header-bar>
<ion-content>
<div class="modal">
<ion-header-bar>
<h1 class="title">Login</h1>
</ion-header-bar>
<ion-content>
<form ng-submit="doLogin()">
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" ng-model="loginData.username" required>
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="loginData.password" required>
</label>
<label class="item">
<button class="button button-block button-positive" type="submit">Log in</button>
</label>
</div>
</form>
</ion-content>
</div>
</ion-content>
</ion-pane>
</body>
</html>
and this is my angular code
angular.module('loginform.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal) {
// Form data for the login modal
$scope.loginData = {};
// Create the`enter code here` login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
if($scope.loginData.username === users.username && $scope.loginData.password===users.password)
alert("Welcome");
};
})
.controller('PlaylistsCtrl', function($scope) {
$scope.users = [
{ username: 'Marwan ', password:'taro', course1:'software engineering', course2:'Web Dev' id: 1 },
{ username: 'Galal', password:'1234', course1:'software engineering' course2:'workflow engines' id: 2 },
];
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
});
$location.path('/newpath') will let you redirect. Inject the $location service in your controller and call the $location.path function at the place of your alert.
Hi try this example this will help you:
login.html:
<div class="container" data-ng-controller="login as vm">
<form class="login">
<p>
<label for="login">Email:</label>
<input type="text" name="login" id="login" data-ng-model="log.email" placeholder="aaa#gmail.com" required>
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" data-ng-model="log.password" placeholder="Password" required>
</p>
<p class="login-submit">
<button type="submit" class="login-button" data-ng-click="vm.login(log)">Login</button>
</p>
<p class="forgot-password">Forgot your password?</p>
</form>
login.js
(function () {
'use strict';
var controllerId = 'login';
angular.module('app').controller(controllerId, ['common', 'loginservice', '$location', '$rootScope', login]);
function login(common, loginservice, $location, $rootScope) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var loggedIn;
var vm = this;
vm.title = 'login';
vm.login = function (log) {
loginservice.getLoginData(log.email, log.password, vm.loginsuccess);
}
vm.loginsuccess = function (data) {
if (data == null) {
toastr.error('Invalid username and password');
}
else {
sessionStorage.Id = data;
loggedIn = data;
$location.path('/dashboard');
$rootScope.$broadcast('logindata', data);
}
}
activate();
function activate() {
common.activateController([], controllerId)
.then(function () { log('Activated login View'); });
$rootScope.$broadcast('logindata', 0);
}
}
})();
loginservice.js
(function () {
'use strict';
var serviceId = 'loginservice';
angular.module('app').factory(serviceId,
['common', loginservice]);
function loginservice(common) {
var $q = common.$q;
var service = {
getLoginData: getLoginData,
};
return service;
function getLoginData(email, password,success) {
var data;
if (email === 'parthi' && password === '12345') {
data= 1;
}
else
data = null;
return success(data);
}
}
})();