How can I fix this Angular $scope issue? - javascript

I have a partial that uses one controller called CaseNotesCtrl. I am having problems accessing $scope variables inside of this partial. The code is this:
<div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotesCtrl">
<div class="col-sm-12 note
-field" ng-show="$parent.addingNote">
<label for="noteEntry">Enter your note</label>
<textarea class="form-control" name="noteEntry" rows="4" ng-model="newNote.note"></textarea>
<br />
</span>
<a href="" data-toggle="tooltip" data-placement="top" title="Cancel Adding Note" class="btn btn-xs btn-danger calicon-view note-cancel-button" ng-click="$parent.cancelNote();" tooltip>
<span class="glyphicon glyphicon-remove-sign"></span>
</a>
</div>
<div class="col-sm-12">
<a href="" data-toggle="tooltip" data-placement="top" title="Add a Note" class="btn btn-xs btn-danger calicon-view note-add-button" ng-click="$parent.addNote();" ng-show="!$parent.addingNote" tooltip>
<span class="glyphicon glyphicon-list-alt"></span>
</a>
</div>
<div class="col-sm-12 note-list-heading" ng-repeat-start="note in caseNotes">
<span class="note-header">Note entered by {{ note.User.DisplayName }} and was last edited on {{ note.ModifiedDate | date: "MM/dd/yyyy 'at' h:mma" }}</span></span>
</div>
<div class="col-sm-12 note-text">
{{ note.Notes }}
</div>
<div ng-repeat-end></div>
</div>
here is the controller code:
JBenchApp.controller('CaseNotesCtrl', ['$scope', '$http', '$routeParams', 'HoldState', function ($scope, $http, $routeParams, HoldState) {
// Management of case notes
$scope.NotesCaseID = $routeParams.number;
$scope.NotesUserName = localStorage.getItem('UserName');
$scope.NotesUserRole = localStorage.getItem('UserRole');
$scope.addingNote = false;
$scope.newNote = { note: 'Testing 123', CaseID: 0, NoteID: 0 };
$scope.getCaseNotes = function (CaseID, UserName, UserRole) {
$http.get('http://10.34.34.46/BenchViewServices/api/CaseNote/' + CaseID + "/" + UserRole + "/" + UserName).success(function (response) {
$scope.caseNotes = response;
})
};
$scope.saveCaseNotes = function (CaseID, UserName, NoteID) {
$scope.addingNote = false;
};
$scope.addNote = function () {
$scope.addingNote = true;
};
$scope.cancelNote = function () {
$scope.newNote.note = '';
$scope.addingNote = false;
};
$scope.editNote = function(caseID, noteID, noteText){
$scope.newNote.note = noteText;
$scope.newNote.CaseID = caseID;
$scope.newNote.NoteID = noteID;
$scope.addingNote = true;
$parent.addingNote = true;
};
$scope.getCaseNotes($scope.NotesCaseID, $scope.NotesUserName, $scope.NotesUserRole);
}]);
As you can see I am having to use $parent in places such as $parent.addingNote. If I change that to $scope.addingNote the function isn't called. The only place I am OK with $parent is $parent.isLoggedIn. How can I fix this so that it just uses $scope?

I would suggest you to use the AngularJS "Controller as" syntax when using ng-controller.
In this case it would be something like this:
app.controller('CaseNotesCtrl', function () {
this.title = 'Some title';
});
<div ng-controller="CaseNotesCtrl as caseNotes">
{{ caseNotes.title }}
</div>
So you it would be easy to you to know which scope are you working with.

Related

ng-click in modal not calling function in component

I am trying to figure out how to get this working.
I am using AngularJS because I do not want to load the complete NPM of Angular and we are using Razor Syntax extensively for the Web Layer
On the Create.cshtml page
<button type="button" ng-click="addApp('Cheese')"
class="btn-sm btn-default no-modal">
Add Applications
</button>
Below is how I have the directory stucture is as follows:
WebLayer
+--wwwroot
+--js
+--applications (Feature)
+applications.component.js
+applications.module.js
+application.template.html
+--delegates (Feature)
+delegates.component.js
+sames as above
+--sponsor-applictions
+same as above
+--lib
+angularjs and all other angularjs files
+app.config.js
+app.module.js
Now I have no problems with getting data below in the sponsor-applictions.component.js I am getting my JSON Object Models arrays from my API.
//Author Moojjoo
//Date 5/3/2019
//sponsor-applications
'use strict';
var testUrl = window.location.hostname;
if (testUrl.includes("localhost")) {
var apiUrl = 'https://localhost:44364';
}
else if (testUrl.includes("uat")) {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for UAT
}
else {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for PRD
}
// Register `sponsorApplications` component, along with its associated controller and template
angular.
module('App').
component('sponsorApplications', {
templateUrl: '../../js/sponsor-applications/sponsor-applications.template.html',
controller: ['$scope', '$http', function SponsorApplications($scope, $http) {
var user_id = $("#User_Id").val();
if (user_id != "") {
$http.get(apiUrl + '/api/v1/Sponsors/' + user_id + '/Applications').then(function successCallback(response) {
$scope.sponsorApplications = response.data;
console.log($scope.sponsorApplications);
}, function errorCallback() {
//var type = 'warning';
//var title = 'User Lookup Required!';
//var body = 'Please enter a User Login ID for lookup'
alert('Please try again later, network error, email sent to application administrator')
});
}
//TODO - Have to get rows from Modal to Page
// Add Rows
$scope.addApp = function (arg) {
debugger;
console.log(arg);
alert(arg);
//$scope.table.push($scope.newApp);
// $scope.newApp = new Object();
};
// Remove Rows
$scope.remove = function (index) {
debugger;
$scope.sponsorApplications.splice(index, 1);
};
}
]
});
I am banging my head against the keyboard trying to figure out why the addApp('Cheese') will not event for for ng-click. $scope.remove function works without any issues.
I really need to understand what I am missing. Thank you and if you need more details simply add a comment.
Edit adding full code
app.config
'use strict';
angular.
module('App').
config(['$routeProvider',
function config($routeProvider) {
$routeProvider.
when('/Sponsors/Create', {
template: '<sponsor-applications></sponsor-applications>'
}).
when('/Sponsors/Create', {
template: '<applications></applications>'
}).
when('/Sponsors/Create', {
template: '<sponsor-delegates></sponsor-delegates>'
}).
when('/Sponsors/Create', {
template: '<delegates></delegates>'
})
}
]);
app.module.js
'use strict';
angular.module('App', [
'ngRoute',
'sponsorApplications',
'applications',
'sponsorDelegates',
'delegates'
])
.run(function () {
console.log('Done loading dependencies and configuring module!');
});
sponsor-applications.component.js
//Author Robert B Dannelly
//Date 4/8/2019
//sponsor-applications
'use strict';
var testUrl = window.location.hostname;
if (testUrl.includes("localhost")) {
var apiUrl = 'https://localhost:44364';
}
else if (testUrl.includes("uat")) {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for UAT
}
else {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for PRD
}
// Register `sponsorApplications` component, along with its associated controller and template
angular.
module('App').
component('sponsorApplications', {
templateUrl: '../../js/sponsor-applications/sponsor-applications.template.html',
controller: ['$scope', '$http', function SponsorApplications($scope, $http) {
var user_id = $("#User_Id").val();
if (user_id != "") {
$http.get(apiUrl + '/api/v1/Sponsors/' + user_id + '/Applications').then(function successCallback(response) {
$scope.sponsorApplications = response.data;
console.log($scope.sponsorApplications);
}, function errorCallback() {
//var type = 'warning';
//var title = 'User Lookup Required!';
//var body = 'Please enter a User Login ID for lookup'
alert('Please try again later, network error, email sent to application administrator')
});
}
//TODO - Have to get rows from Modal to Page
// Add Rows
$scope.addApp = function (arg) {
debugger;
console.log(arg);
alert(arg);
//$scope.table.push($scope.newApp);
// $scope.newApp = new Object();
};
// Remove Rows
$scope.remove = function (index) {
debugger;
$scope.sponsorApplications.splice(index, 1);
};
}
]
});
sponsor-applications.module.js
'use strict';
// Define the `sponsorApplicaitons` module
angular.module('sponsorApplications', []);
sponsor-applications.template.html
<style>
/* Overwrites */
.btn {
width: 100%;
}
</style>
<table class="table-bordered table-striped" style="width:100%;">
<thead style="font-weight:bold">
<tr>
<td>Remove</td>
<td>Application ID</td>
<td>Application Name</td>
</tr>
</thead>
<!-- The naming must be exact application matches the $scope.sponsorApplications
in sponsor-applications.component.js-->
<tr ng-repeat="app in sponsorApplications">
<td>
<a class="btn" ng-click="remove($index)"><i class="fa fa-times" aria-hidden="true"></i></a>
</td>
<td>{{ app.application_ID }}</td>
<td>{{ app.application_Name }}</td>
</tr>
</table>
Create.cshtml -- ASP.NET Core w/ Razor Syntax ----
#model WEB.ViewModels.AddSponsorViewModel
#using WEB.HtmlHelpers
#{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- Alert Display will be used as a standard on all page simply add this to your page
https://www.trycatchfail.com/2018/01/22/easily-add-bootstrap-alerts-to-your-viewresults-with-asp-net-core/
https://www.trycatchfail.com/2018/02/21/easy-bootstrap-alerts-for-your-api-results-with-asp-net-core/-->
#await Html.PartialAsync("~/Views/Shared/_StatusMessages.cshtml")
<h2>Sponsor Information</h2>
<form asp-action="Create" id="CreateSponsor">
#Html.AntiForgeryToken()
#*<input type=hidden asp-for="User_ID" />*#
<input type="hidden" id="User_Id" name="User_Id" value="" />
<div class="form-horizontal">
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-12">
<row>
<div class="form-group col-md-5">
<label asp-for="Domain_ID" class="control-label"></label>
<br />
<input asp-for="Domain_ID" class="form-control" />
<span asp-validation-for="Domain_ID" class="text-danger"></span>
</div>
<div class="col-md-2">
</div>
<div class="form-group col-md-5">
<label asp-for="Name" class="control-label"></label>
<br />
<input asp-for="Name" class="form-control" />
#*#Html.AutocompleteFor(model => Core.Models.SearcherUser.Name, model => Core.Models.SearcherUser.Email, "GetSponsor", "Approval", false)*#
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</row>
</div>
<div class="col-md-12">
<row>
<div class="form-group col-md-12">
<label asp-for="Email" class="control-label"></label>
<br />
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</row>
</div>
<div class="col-md-12" style="margin-top:20px">
<row>
<div class="col-md-6">
<strong>Delegates</strong> <asp:button formnovalidate="formnovalidate" id="addDelegate" style="cursor: pointer" class="btn-xs btn-primary" data-toggle="modal" data-target="#delegatesModal">Add</asp:button>
<!-- AngularJS defined in wwwroot > js > sponsor-applications -->
<sponsor-delegates></sponsor-delegates>
</div>
<div id="divMyAppCtrl" class="col-md-6">
<strong>Applications</strong> <asp:button formnovalidate="formnovalidate" id="addApplication" style="cursor: pointer" class="btn-xs btn-primary" data-toggle="modal" data-target="#appModal">Add</asp:button>
<!-- AngularJS defined in wwwroot > js > sponsor-applications -->
<br />
<sponsor-applications></sponsor-applications>
</div>
</row>
</div>
<div class="col-md-12" style="margin-top:50px;">
<row>
<div class="col-md-2">
<input type="submit" value="Delete" disabled class="btn btn-default" />
</div>
<div class="col-md-offset-6 col-md-2" style="text-align:right">
<input type="submit" value="Save" class="btn btn-default" />
</div>
<div class="col-md-2">
<button class="btn btn-default" type="button" id="cancel" onclick="location.href='#Url.Action("Index", "Sponsors")'">Cancel</button>
</div>
</row>
</div>
</div>
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
<!-- Modal to select delegates for sponsor -->
<div class="modal fade" tabindex="-1" role="dialog" id="delegatesModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<strong>Please select the Delegates</strong>
<div id="delgates_tbl">
<!-- AngularJS defined in wwwroot > js > applications -->
<delegates></delegates>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-sm btn-default no-modal" data-dismiss="modal" id="closeDelegate">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Add Applications Button in Modal
<!-- Modal to select application for sponsor -->
<div class="modal fade" tabindex="-1" role="dialog" id="appModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<strong>Please select the applications</strong>
<div id="divModalApps">
<!-- AngularJS defined in wwwroot > js > applications -->
<applications></applications>
</div>
</div>
<div class="modal-footer">
<button type="button"
ng-click="addApp('Cheese')"
class="btn-sm btn-default no-modal">
Add Applications
</button>
<button type="button" class="btn-sm btn-default no-modal"
data-dismiss="modal" id="closeApps">
Close
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
----
the button HTML is on the Create.cshtml page, but so are all the templates aka
<sponsor-applications>
</sponsor-applications>
Also note that in the _Layouts.cshtml page all js files are referenced. ~/app.module.js, ~/app.config.js, ~/js/sponsor-delegates/sponsor-delegate.module.js, ~/js/sponsor-delegates/sponsor-delegates.component.js
sponsor-applications.component.js
//Author Robert B Dannelly
//Date 4/8/2019
//sponsor-applications
'use strict';
var testUrl = window.location.hostname;
if (testUrl.includes("localhost")) {
var apiUrl = 'https://localhost:44364';
}
else if (testUrl.includes("uat")) {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for UAT
}
else {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for PRD
}
// Register `sponsorApplications` component, along with its associated controller and template
angular.
module('App').
component('sponsorApplications', {
templateUrl: '../../js/sponsor-applications/sponsor-applications.template.html',
controller: ['$scope', '$http', function SponsorApplications($scope, $http) {
var user_id = $("#User_Id").val();
if (user_id != "") {
$http.get(apiUrl + '/api/v1/Sponsors/' + user_id + '/Applications').then(function successCallback(response) {
$scope.sponsorApplications = response.data;
console.log($scope.sponsorApplications);
}, function errorCallback() {
//var type = 'warning';
//var title = 'User Lookup Required!';
//var body = 'Please enter a User Login ID for lookup'
alert('Please try again later, network error, email sent to application administrator')
});
}
//TODO - Have to get rows from Modal to Page
// Add Rows
**********************BELOW is the correct SYNTAX********************
this.addApp = function (arg) {
alert(arg);
debugger;
console.log(arg);
};
//$scope.addApp = function (arg) {
// debugger;
// console.log(arg);
// alert(arg);
// //$scope.table.push($scope.newApp);
// // $scope.newApp = new Object();
//};
// Remove Rows
$scope.remove = function (index) {
debugger;
$scope.sponsorApplications.splice(index, 1);
};
}
]
});
Create.cshtml Changes
In the template
<div id="divMyAppCtrl" class="col-md-6">
<strong>Applications</strong> <asp:button formnovalidate="formnovalidate" id="addApplication" style="cursor: pointer" class="btn-xs btn-primary" data-toggle="modal" data-target="#appModal">Add</asp:button>
<!-- AngularJS defined in wwwroot > js > sponsor-applications -->
<br />
<sponsor-applications ng-ref="sponsorApplications"></sponsor-applications>
</div>
Add Applications Modal in the footer
<div class="modal-footer">
<button type="button" ng-click="sponsorApplications.addApp('CLicked')" class="btn-sm btn-default no-modal">Add Applications</button>
<button type="button" class="btn-sm btn-default no-modal" data-dismiss="modal" id="closeApps">Close</button>
</div>

Clear ng-src using ng-click

I have problem with clear ng-src (input file) using ng-click. I would like solve this problem using angular. I tried use angular.element.val('') but this is not good solution for me. Do you know another way?
controller.js
app.imagePreview = false;
$scope.thumbnail = {
dataUrl: null
};
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function(files){
if (files != null) {
var file = files[0];
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function() {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(e) {
$timeout(function(){
$scope.thumbnail.dataUrl = e.target.result;
app.imagePreview = true;
});
}
});
}
}
};
app.clearImage = function(){
$scope.thumbnail = {
dataUrl: null
};
}
index.html
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-picture-o"></i>
</div>
<input type="text" class="form-control" readonly>
<span class="input-group-btn">
<span class="btn btn-default btn-file add-img-upload">
<a id="clearPreview" type="button" ng-click="product.clearImage()">
<span class="glyphicon glyphicon-remove"></span> UsuĊ„
</a>
</span>
<span class="btn btn-default btn-file add-img-upload"><span class="glyphicon glyphicon-folder-open"></span> Wybierz
<input type="file" name="file" id="imgInp" onchange="angular.element(this).scope().photoChanged(this.files)" ng-model="files">
</span>
</span>
</div>
<img ng-if="product.imagePreview" ng-src="{{ thumbnail.dataUrl }}" id='img-upload'/>
</div>
In your controller you've named the method app.clearImage and in your html, you're calling product.clearImage. Rename one of them so that they match and it should work.
I believe you really just want clearImage to be a method of your controller. Removing "product." in front of it in your html and chanding "app." in front of it in your controller to "$scope." should also work.
in your html:
and in your controller:
$scope.clearImage = function(){
$scope.thumbnail = {
dataUrl: null
};
}

How can I store an array of chat messages in local storage and how can I retrieve them back in angularjs?

Iam working with chat application.Here I have to store the messages in local storage those entered by individual user as well as group messages also.So I want to use local storage inorder to store the messages so that when I click on the particular user,previous messages sent by that user has to be shown.Iam strucked at writing code for this.How can I implement this code in javascript?
Here is my entire code:
var grp = angular.module("grpApp", [])
.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('{|');
$interpolateProvider.endSymbol('|}');
})
.directive('scrollBottom', function () {
return {
scope: {
scrollBottom: "="
},
link: function (scope, element) {
scope.$watchCollection('scrollBottom', function (newValue) {
if (newValue) {
$(element).scrollTop($(element)[0].scrollHeight);
}
});
}
}
})
.controller("grpCtrl", function ($scope) {
document.getElementById("name").innerHTML = "Group";
$scope.friendsList = ["Devi", "Teja", "Sneha", "Srujana"];
$scope.msgdata = [];
var d = new Date();
$scope.time = d.toLocaleString();
console.log("hlooo" + $scope.time);
//$scope.uname=JSON.parse($stateParams.uname);
document.getElementById("clear").addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
document.getElementById("submitmsg").click();
}
});
$scope.send = function () {
document.getElementById("submitmsg").disabled = false;
var retData = localStorage.getItem("storedData");
console.log("hiieeee" + retData);
var retrieveData = JSON.parse(retData);
console.log("heloooo" + retrieveData);
$scope.msgdata.push(retrieveData);
$scope.msgdata.push($scope.message + " " + " " + $scope.time);
$scope.message = "";
console.log("hi" + $scope.msgdata);
}
$scope.showGrp = function () {
document.getElementById("name").innerHTML = "Group";
$scope.msgdata = [];
var preData = $scope.msgdata;
localStorage.setItem("storedData", JSON.stringify(preData));
}
$scope.frndgrp = function (frnd) {
document.getElementById("name").innerHTML = frnd;
$scope.msgdata = [];
var preData = $scope.msgdata;
localStorage.setItem("storedData", JSON.stringify(preData));
}
});
<div class="container-fluid">
<div class="row content">
<div class="col-sm-4 sidenav" id="divlength" style="height:600px;overflow-y:scroll">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search friend.." ng-model="search">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
<br>
<button class="btn btn-primary btn-lg" style="width:50%" ng-click="showGrp()">Group</button>
<br>
<br>
<div class="nav nav-pills nav-stacked" ng-repeat="frnd in friendsList|filter:search">
<a class="btn btn-primary" style="width:50%" ng-bind="frnd" ng-click="frndgrp(frnd)"></a>
<br>
<br>
</div>
<br>
</div>
<div class="col-sm-8" style="height:100px">
<h4 align="center" id="name" style="font-weight:bold"></h4>
<footer id="wrapper">
<div class="chatbox">
<div class="chatBox" scroll-bottom="msgdata" id="clearmsg">
<div ng-repeat="item in msgdata track by $index"><span class="btn" id="msg" style="background-color:lightgreen;color:black; margin-bottom:5px" ng-bind="item"></span>
</div>
</div>
</div>
<div class="input-group add-on" style="width:100%;">
<input class="form-control usermsg chatTextField" placeholder="Type a message" name="srch-term" type="text" ng-model="message" id="clear" required>
<div class="input-group-btn">
<button class="btn btn-success" type="submit" style="float:right" id="submitmsg" ng-click="send()" ng-disabled="!message"><span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</footer>
</div>
</div>
</div>

Different values stored storing a string with localStorage and $localStorage with Angular 1.

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]);
}
});

ng-model doesnt bind with text field

Consider the following JS
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}
);
And the following HTML
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
My problem is that when the page loads, "test" is written in the text field, but when I change the field or press the button, nothing happens (console says "test" on every change or button click. Anyone know what I did wrong?
Try to wrap the value in an object. Objects are passed by reference, but simple values are passed as a copy of that value. It happened to me too several times.
Try this approach
$scope.myObject.searchBooking = "test"
So the full code will look like this
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.myObject.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.myObject.searchBooking);
//$location.path('/bookings/' + $scope.myObject.searchBooking);
//delete($scope.myObject.searchBooking);
}
$scope.printValue = function() {
console.log($scope.myObject.searchBooking);
}
}
);
and the html
<input type="text" class="form-control" placeholder="Testing" ng-model="myObject.searchBooking" ng-change="printValue()">
Find this fiddle which is having ng-model binding in ng-change.
HTML
<div ng-controller="MyCtrl">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
Angular controller
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}

Categories