ng-disabled nor enabling Submit button - javascript

I hope you can help me.
I think I am missing something, and just can't figure it out. For some reason I cannot get ng-disabled="formSubmmision" to enable the button when the form has been filled in.
Any help will be greatly appreciated!
I have the following view and controller:
Here is my view:
<section class="mainbar" data-ng-controller="adminVendorNumberController as vm">
<article class="booty">
<div class="row-fluid">
<div class="col-md-12">
<h1 class="main-heading"><strong>Vendor Number Admin</strong></h1>
</div>
</div>
<form name="formInsertVendorNumber" novalidate>
<div class="row-fluid island">
<div class="col-md-12">
<div>
<!--Here-->
<div class="header">
<div class="green"><span class="icon-user-tie"></span></div>
<h2 class="title">Add New <strong>Vendor Number</strong></h2>
</div>
<div class="row-fluid">
<!-- Customer-->
<div class="col-md-4">
<label>Vendor</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select Vendor"
ng-model="NewVendorNumber.Vendor"
ng-disabled="false"
ng-options="vendorData"
cc-fields="VendorDescription"
cc-key-field="VendorId"
cc-allow-search="false"
ng-required="false"
ng-change="vendorSelected()"
name="iVendor">
</cc-dropdown>
</div>
</div>
<!-- End Customer-->
<!--Region -->
<!-- Update: ng-disabled="NewVendorNumber.Vendor == null" -->
<div class="col-md-4">
<label>Item Group</label>
<div class="input-dropdown">
<cc-dropdown cc-placeholder="Select Item Group"
ng-model="NewVendorNumber.ItemGroup"
ng-disabled="NewVendorNumber.Vendor == null"
ng-options="itemGroupData"
cc-fields="ItemGroupDescription"
cc-key-field="ItemGroupId"
cc-allow-search="false"
ng-required="false"
ng-change="itemGroupSelected()"
name="iItemGroup">
</cc-dropdown>
</div>
</div>
<!--End Region -->
<div class="col-md-4">
<label>Vendor Item Number</label>
<div class="input-text">
<input type="text" name="iVendorItemNumber" required ng-model="NewVendorNumber.ItemNumber" />
<div class="errorIcon fadeInOut" ng-class="{error : VendorItemError}" ng-mouseenter="VendorItemError = true" ng-mouseleave="VendorItemError = false"
ng-show="(formInsertVendorNumber.$submitted || formInsertVendorNumber.iVendorItemNumber.$touched) && formInsertVendorNumber.iVendorItemNumber.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please enter a Vendor Item Number</span>
</p>
</div>
</div>
</div>
</div>
<div class="col-md-8">
<label>Vendor Item Description</label>
<div class="input-text">
<input type="text" name="iVendorItemDescription" required ng-model="NewVendorNumber.ItemDescription" />
<div class="errorIcon fadeInOut" ng-class="{error : VendorItemDescriptionError}" ng-mouseenter="VendorItemDescriptionError = true" ng-mouseleave="VendorItemDescriptionError = false"
ng-show="(formInsertVendorNumber.$submitted || formInsertVendorNumber.iVendorItemDescription.$touched) && formInsertVendorNumber.iVendorItemDescription.$error.required">
<span class="icon-warning"></span>
<div>
<p>
<span>Please enter a Vendor Item Description</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="separator"></div>
<div class="footer">
<!-- Update: ng-disabled="formSubmmision" -->
<button type="submit" class="btn btn-default right" ng-click="save()" ng-disabled="formSubmmision"><span class="icon-checkmark"> </span>Save</button>
</div>
</div>
</div>
</div>
</form>
</article>
</section>
Here is my controller:
(function () {
"use strict";
angular
.module('app.adminVendorNumber')
.controller('adminVendorNumberController', adminVendorNumberController);
adminVendorNumberController.$inject = ['$http', 'logger', '$scope'];
function adminVendorNumberController($http, logger, $scope) {
var vm = $scope;
vm.formSubmmision = true;
vm.vendorItemData = null;
vm.itemGroupData = null;
vm.vendorData = null;
vm.vendorSelected = vendorSelected;
vm.itemGroupSelected = itemGroupSelected;
vm.save = save;
activate();
function activate() {
return vendorItemData().then(getAllItemGroups).then(getVendorData).then(function () {
logger.info('Activated Vendor Number Creation');
});
}
function vendorItemData(data) {
return $http.get('/api/vendorItem/getAll/')
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorItemData = responce.data.Records;
return vm.vendorItemData;
}
function Failure(error) {
logger.error('Failed to Get Customer Data ' + error.data.Message);
}
}
function getVendorData(data) {
return $http.get('/api/vendor/GetAllVendors/')
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorData = responce.data.Records;
return vm.vendorData;
}
function Failure(error) {
logger.error('Failed to Get Vendor Data ' + error.data.Message);
}
}
function getAllItemGroups(data) {
return $http.get('/api/itemGroup/GetAllItemGroups/')
.then(Success)
.catch(Failure);
function Success(response) {
vm.itemGroupData = response.data.Records;
return vm.itemGroupData;
}
function Failure(error) {
logger.error('Failed to Get Item Group Data ' + error.data.Message);
}
}
// Form Selections
function itemGroupSelected() {
vm.formSubmmision = true;
return getItemGroupById(vm.NewVendorNumber.ItemGroup.ItemGroupId);
}
function getItemGroupById(itemGroupId) {
return $http.get("/api/itemGroup/GetItemGroupById/?itemGroupId=" + itemGroupId)
.then(Success)
.catch(Failure);
function Success(responce) {
vm.itemGroupSelected = responce.data.Records;
return vm.itemGroupSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
function vendorSelected() {
vm.formSubmmision = true;
return getVendorById(vm.NewVendorNumber.Vendor.VendorId);
}
function getVendorById(vendorId) {
return $http.get("/api/vendor/ReadVendor/?vendorid=" + vendorId)
.then(Success)
.catch(Failure);
function Success(responce) {
vm.vendorSelected = responce.data.Records;
return vm.vendorSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
// Save
function save() {
if (vm.formInsertVendorNumber.$valid) {
postNewData();
}
else {
logger.error('Error: Validation failed. Please correct data and try again');
vm.formSubmmision = false;
}
}
function postNewData() {
//prepare data
var data = {
VendorItemId: 0,
ItemNumber: vm.NewVendorNumber.ItemNumber,
ItemDescription: vm.NewVendorNumber.ItemDescription,
ItemType: "",
OnCall: "",
Vendor: {
VendorId: vm.NewVendorNumber.Vendor.VendorId,
VendorDescription: vm.NewVendorNumber.Vendor.VendorDescription,
Active: vm.NewVendorNumber.Vendor.Active,
Id: vm.NewVendorNumber.Vendor.Id,
ChangedDate: vm.NewVendorNumber.Vendor.ChangedDate
},
ItemGroup: {
ItemGroupId: vm.NewVendorNumber.ItemGroup.ItemGroupId,
ItemGroupDescription: vm.NewVendorNumber.ItemGroup.ItemGroupDescription,
Id: vm.NewVendorNumber.ItemGroup.Id,
ItemCodeGroup: vm.NewVendorNumber.ItemGroup.ItemCodeGroup
}
}
$http.post('/api/vendorItem/PostVendorItem/', data)
.then(postDataComplete)
.catch(getDataFailed);
function postDataComplete(response) {
logger.info("Vendor Item Number Created ");
vm.NewVendorNumber = null;
vm.formSubmmision = true;
vm.formInsertVendorNumber.$setPristine();
vm.formInsertVendorNumber.$setUntouched();
return vm.NewVendorNumber;
}
function getDataFailed(error) {
logger.error('Failed to Vendor Item Number ' + error.data.Message);
return;
}
}
};
}
)();

you are using CONTROLLER AS syntax.
Your controller should be ...
var vm = this;
NOT ...
var vm = $scope;
also you should be using ...
formInsertVendorNumber.$valid to disable or enable the submit button.
you should, inside your form, display ...
<span>{{ formInsertVendorNumber }}</span>
This will output a lot of angular variables associated with the form. You should see that formInsertVendorNumber.$valid is true when the form is valid and false when it is not. use that to toggle your button.

I solved my problem by adding another simple function called formSubmit() to my controller:
function getItemGroupById(itemGroupId) {
return $http.get("/api/itemGroup/GetItemGroupById/?itemGroupId=" + itemGroupId)
.then(Success)
.then(formSubmit)
.catch(Failure);
function Success(responce) {
vm.itemGroupSelected = responce.data.Records;
return vm.itemGroupSelected, responce.data;
}
function Failure(error) {
logger.error('Failed to get Vendor Data ' + error.data.Message);
}
}
function formSubmit() {
vm.formSubmmision = false;
return vm.formSubmmision;
}

Related

Uncaught TypeError: Unable to process binding "if" with knockout

I am simply trying to create some checkboxes and inputs that get the data from database and saving it back to database after edit. But I am getting the following error:
Uncaught TypeError: Unable to process binding "if: function(){return $root.editAlarmValues }"
Message: Unable to process binding "enable: function(){return $root.editAlarmValues().setAlarmValues() }"
Message: $root.editAlarmValues(...).setAlarmValues is not a function
I am not sure what I am doing wrong. I checked in the console and the values get mapped correctly to the array but they don't seem to bind to view. Any help will be highly appreciated!
Here is the code:
<!--ko if: $root.editAlarmValues -->
<div class="row">
<div class="col-md-6">
<input type="checkbox" data-bind="iCheck: $root.editAlarmValues().setAlarmValues" class="large-check"/>
</div>
</div>
<div class="row">
<div class="col-md-5 form-inline">
<input type="checkbox" data-bind="iCheck: $root.editAlarmValues().setOutputCurrentPPLowValue, enable: $root.editAlarmValues().setAlarmValues()" class="large-check"/>
<input type="text" id="OutputCurrentPPLowValue" data-bind="value: $root.editAlarmValues().outputCurrentPPLowValue, enable: $root.editAlarmValues().setOutputCurrentPPLowValue()" class="form-control" maxlength="30" />
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="pull-right">
<button type="button" class="btn btn-primary btn-flat" data-bind="event: {click: $root.editSave}">Save</button>
</div>
</div>
</div>
<!-- /ko -->
and script:
var AlarmsViewModel = function (wellID) {
function EditAlarms(setAlarmValues, setOutputCurrentPPLowValue, outputCurrentPPLowValue) {
var self = this;
self.setAlarmValues = ko.observable(setAlarmValues);
self.setOutputCurrentPPLowValue = ko.observable(setOutputCurrentPPLowValue);
self.outputCurrentPPLowValue = ko.observable(outputCurrentPPLowValue);
}
var self = this;
self.wellID = ko.observable(wellID);
self.editAlarmValues = ko.observableArray();
self.init = function () {
self.editAlarmInit();
};
self.editAlarmInit = function () {
APIHelper.getData("/api/alarmapi/EditAlarms?wellID=" + self.wellID(), self.editAlarmsCallback, "");
};
self.editAlarmsCallback = function (data) {
//Map results
var temp = $.map(data.result, function (item) {
return new EditAlarms(item.setAlarmValues, item.setOutputCurrentPPLowValue, item.outputCurrentPPLowValue);
});
self.editAlarmValues(temp);
};
self.editSave = function () {
var jsonData = ko.toJSON(self.editAlarmValues);
APIHelper.postData("/api/alarmapi/EditAlarmsPost", jsonData);
};
self.init();
};
var wellID = #ViewBag.WellID;
ko.bindingHandlers.iCheck = {
init: function (el, valueAccessor) {
var observable = valueAccessor();
$(el).on("ifChanged", function () {
observable(this.checked);
});
},
update: function (el, valueAccessor) {
var val = ko.utils.unwrapObservable(valueAccessor());
if (val) {
$(el).iCheck('check');
} else {
$(el).iCheck('uncheck');
}
}
};
var vm = new AlarmsViewModel(wellID);
ko.applyBindings(vm);
You don't want a <!-- ko if: editAlarmValues -->, you want a <!-- ko foreach: editAlarmValues -->. The foreach will not run when the target array is empty, so it fundamentally fulfills the same function.
Inside the foreach, the binding context is the EditAlarms object in question, so you should refer to its properties directly (iCheck: setOutputCurrentPPLowValue instead of iCheck: $root.editAlarmValues().setOutputCurrentPPLowValue).
Also think about your naming. EditAlarms is not a good name for a single object. The prefix set... should refer to a method that sets something. In this case it's just an observable property. setAlarmValues should be called alarmValues, and because it's not an array, it probably should actually be called alarmValue. And so on.
<!-- ko foreach: editAlarmValues -->
<div class="row">
<div class="col-md-6">
<input type="checkbox" data-bind="iCheck: setAlarmValues" class="large-check">
</div>
</div>
<div class="row">
<div class="col-md-5 form-inline">
<input type="checkbox" class="large-check" data-bind="
iCheck: setOutputCurrentPPLowValue,
enable: setAlarmValues
">
<input type="text" id="OutputCurrentPPLowValue" class="form-control" maxlength="30" data-bind="
value: outputCurrentPPLowValue,
enable: setOutputCurrentPPLowValue
">
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="pull-right">
<button type="button" class="btn btn-primary btn-flat" data-bind="click: $root.editSave">Save</button>
</div>
</div>
</div>
<!-- /ko -->
Revised JS code (move the binding handler definitions to the top, don't nest viewmodels)
ko.bindingHandlers.iCheck = {
init: function (el, valueAccessor) {
var observable = valueAccessor();
$(el).on("ifChanged", function () {
observable(this.checked);
});
},
update: function (el, valueAccessor) {
var val = ko.unwap(valueAccessor());
$(el).iCheck(val ? 'check' : 'uncheck');
}
};
function EditAlarms(setAlarmValues, setOutputCurrentPPLowValue, outputCurrentPPLowValue) {
this.setAlarmValues = ko.observable(setAlarmValues);
this.setOutputCurrentPPLowValue = ko.observable(setOutputCurrentPPLowValue);
this.outputCurrentPPLowValue = ko.observable(outputCurrentPPLowValue);
}
function AlarmsViewModel(wellID) {
var self = this;
self.wellID = ko.observable(wellID);
self.editAlarmValues = ko.observableArray();
self.editAlarmInit = function () {
APIHelper.getData("/api/alarmapi/EditAlarms?wellID=" + self.wellID(), function (data) {
var alarms = data.result.map(item => new EditAlarms(
item.setAlarmValues,
item.setOutputCurrentPPLowValue,
item.outputCurrentPPLowValue
));
self.editAlarmValues(alarms);
});
};
self.editSave = function () {
APIHelper.postData("/api/alarmapi/EditAlarmsPost", ko.toJSON(self.editAlarmValues));
};
self.editAlarmInit();
}
var vm = new AlarmsViewModel(#ViewBag.WellID);
ko.applyBindings(vm);

ngClass is not changing color based on variable value

I want to display green text message when value is true, and red text when value is false.
angular app:
at the top of the controller, I declare my variable and initiate it true:
$scope.IsColor = true;
if (response.data.indexOf("Panelists sucessfully added") !== -1) {
$scope.IsColor = true;
$scope.Messages = response.data;
angular.element("#msg").focus()
return true;
}
else {
$scope.IsColor = false;
$scope.Messages = response.data;
angular.element("#msg").focus()
return false;
}
In HTML:
<div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
No matter what response is, either positive or negative, the text always displays in red.
Does anyone have an idea what is wrong here?
Thank you,
Erasmo
UPDATE
More html
<body>
<div class="container pt-5 pb-5">
<div class="row">
<div class="col-md-8">
<div ng-app="MyApp" ng-controller="MyController">
<div>
<input type="button" value="Upload" id="btn-upload" ng-click="Upload()" />
</div>
#* Excel Contents Table *#
<table class="table mt-4 mb-5" id="tblPanelists" ng-show="IsVisible">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tbody ng-repeat="p in Panelists">
<tr>
<td>{{p.Name}}</td>
<td>{{p.Email}}</td>
</tr>
</tbody>
</table>
<div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
<div class=" mt-3">
<button type="submit" class="btn btn-admin-blue" id="btn-add-panelists" ng-click="AddPanelists()"
ng-disabled="disableSubmit">
Submit
</button>
</div>
</div>
</div>
</div>
</div>
</body>
and the angularjs controller-function Add Panelists
The $scope.IsColor boolean is delcare outside the function AddPanelists, within the controller, and used inside the AddPanelists function
AddPanelists function:
$scope.AddPanelists = function () {
$scope.arr = new Array;
angular.forEach($scope.Panelists, function (item) {
var b = {
name: item.Name.trim(),
email: item.Email.trim()
};
$scope.arr.push(b);
});
if ($scope.webinarId !== '') {
if ($scope.arr.length > 0) {
var data = JSON.stringify({ 'panelists': $scope.arr, 'webId': $scope.webinarId.split(' ').join('') });
//Call the services
$http.post('/meetings/panelists/home/createpanelists', data)
.then(function (response) {
if (response.data.indexOf("Panelists sucessfully added") !== -1) {
$scope.IsColor = true;
$scope.Messages = response.data;
angular.element("#msg").focus()
return true;
}
else {
$scope.IsColor = false;
$scope.Messages = response.data;
angular.element("#msg").focus()
return false;
}
}, function (response) {
$scope.IsColor = false;
$scope.Messages = "Service unavailable. Please try again.";
angular.element("#msg").focus()
return false;
});
} else {
$scope.IsColor = false;
alert('Please make sure to select a list of Panelists.');
$scope.Messages = 'Please make sure to select a list of Panelists';
angular.element("#msg").focus()
return false;
}
}
else {
$scope.IsColor = false;
alert('Please make sure to enter an ID');
$scope.Messages = 'Please make sure to enter a Zoom Webinar ID';
angular.element("#msg").focus()
return false;
}
};
Not really an anwser, but there seems to be nothing really wrong as u see in the example.(Except that the $scope.Messages should always be an array instead of string. )
I've tried running your function with a 'mock' http-request, seems to be working fine. You need to check the response that is being returned from the http-request.
angular.module('MyApp', []).controller('MyController', function($scope, $q){
$scope.arr =[1,2,3];
$scope.webinarId = '1234';
$scope.IsColor = false;
function mock(isResolve){
return $q(function(resolve, reject){
setTimeout(function(){
if(isResolve){
resolve({data:['Panelists sucessfully added','message 1', 'message 2']});
}else{
reject({data: ['error 1', 'error 2']});
}
}, 1000);
});
}
$scope.AddPanelists = function () {
angular.forEach($scope.Panelists, function (item) {
var b = {
name: item.Name.trim(),
email: item.Email.trim()
};
$scope.arr.push(b);
});
if ($scope.webinarId !== '') {
if ($scope.arr.length > 0) {
// var data = JSON.stringify({ 'panelists': $scope.arr, 'webId': $scope.webinarId.split(' ').join('') });
//Call the services
// $http.post('/meetings/panelists/home/createpanelists', data)
mock(true).then(function (response) {
if (response.data.indexOf("Panelists sucessfully added") !== -1) {
$scope.IsColor = true;
$scope.Messages = response.data;
angular.element("#msg").focus()
return true;
}
else {
$scope.IsColor = false;
$scope.Messages = response.data;
angular.element("#msg").focus()
return false;
}
}, function (response) {
$scope.IsColor = false;
// this should be an array as $scope.Messages is used in ng-repeat
$scope.Messages = ["Service unavailable. Please try again."];
//angular.element("#msg").focus()
return false;
});
} else {
$scope.IsColor = false;
alert('Please make sure to select a list of Panelists.');
// this should be an array as $scope.Messages is used in ng-repeat
$scope.Messages = ['Please make sure to select a list of Panelists'];
// angular.element("#msg").focus()
return false;
}
}
else {
$scope.IsColor = false;
alert('Please make sure to enter an ID');
// this should be an array as $scope.Messages is used in ng-repeat
$scope.Messages = ['Please make sure to enter a Zoom Webinar ID'];
angular.element("#msg").focus()
return false;
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<div>
<input type="button" value="Upload" id="btn-upload" ng-click="Upload()" />
</div>
#* Excel Contents Table *#
<table class="table mt-4 mb-5" id="tblPanelists" ng-show="IsVisible">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tbody ng-repeat="p in Panelists">
<tr>
<td>{{p.Name}}</td>
<td>{{p.Email}}</td>
</tr>
</tbody>
</table>
<div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
<div class=" mt-3">
<button type="submit" class="btn btn-admin-blue" id="btn-add-panelists" ng-click="AddPanelists()"
ng-disabled="disableSubmit">
Submit
</button>
</div>
</div>

Local storage not shown after refresh

I just can't get it working no matter what I do. Been sitting for hours and nothing. After submitting form I create local storage of values name, surname, email, so that I would be able to use them to fill up form so that user would not have to type them everytime.
submit() is in review.controller.js
(function () {
'use strict';
angular.module('app').controller('ReviewController', ReviewController);
ReviewController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$route','$cookies','localStorageService'];
function ReviewController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$route,$cookies,localStorageService) {
var vm = this;
vm.name = null;
vm.surname = null;
vm.Email = null;
vm.review = null;
vm.allgenres = [];
vm.submit = submit;
vm.allreviews = [];
$scope.localArray=[];
loadAllReviews();
submit();
$scope.templates = [{ name: 'man.main.view.html', url: 'main/main.view.html'}];
$scope.template = $scope.templates[0];
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
$scope.init = function () {debugger;
// $scope.$MainController.obtained_array = localStorage.getItem("storageKey");debugger;
$scope.storageKey = localStorage.getItem("storageKey");debugger;
};
$scope.storageKey = localStorage.getItem('storageKey');
/* $scope.$watch("storageKey", function() {debugger;
localStorage.setItem('storageKey', storageKey);
});*/
function submit() {
if($rootScope.name!=null) {
var JSONObject = {
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email,
"review":$rootScope.review
}
var temp={
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email
}
$scope.localArray.push(temp);
localStorageService.set("storageKey", $scope.localArray);
$scope.storageKey = localStorageService.get("storageKey");
// $rootScope.obtained_array = localStorageService.get("storageKey"); debugger;
console.log($scope.storageKey);debugger;
var Results = UniversalService.PostReview(JSON.stringify(JSONObject));
}
}
}
main.controller.js
'use strict';
var app= angular.module('app').controller('MainController', MainController);
MainController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$log','PagerService','localStorageService','$mdDialog'];
function MainController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$log,PagerService,localStorageService,$mdDialog) {
var vm = this;
vm.allreviews = [];
vm.allusers=[];
vm.allemails=[];
vm.all=[];
vm.avatars=[];
$scope.filteredAll = [];
$scope.all=[];
$scope.items=[];
$scope.pager = {};
$scope.setPage = setPage;
loadAllReviews();
loadAllEmails();
loadAllUsers();
loadAll();
loadAvatars();
initController();
setPage();
submit();
$scope.init = function () {
$scope.$parent.storageKey = localStorage.getItem("storageKey");debugger;
// $scope.obtained_array = localStorage.getItem("storageKey");
// console.log(obtained_array); debugger;
// $scope.storageKey = localStorage.getItem("storageKey");debugger;
};
function refresh() {
location.reload();debugger;
}
function loadAll() {
UniversalService.GetAll()
.then(function (a) {
$scope.all=a;
});
}
function loadAllUsers(callback) {
UniversalService.GetAll()
.then(function (response) {
$scope.users=response;
if (callback) {
callback(response);
}
});
}
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
function loadAllEmails() {
UniversalService.GetAllEmails()
.then(function (email) {
vm.allemails = email;
});
}
function setPage(page) {
loadAllUsers(function (response) {
if (response) {
if (page < 1 || page > $scope.pager.totalPages) {
return;
}
// get pager object from service
$scope.everything=response;
$scope.pager = PagerService.GetPager(response.length, page);
// get current page of items
$scope.items = response.slice($scope.pager.startIndex, $scope.pager.endIndex + 1);
}
});
}
function initController() {
$scope.setPage(1); // initialize to page 1
}
}
HTML file:
<div class="container padding-tb" id="Review">
<div ng-controller="ReviewController" ng-init="init()" ng-app id="Review">
<h2>Add review</h2>
<form name="form" ng-submit="vm.submit()" role="form">
<div >
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="text" ng-model="name" onchange="CallItems()" id="name" class="form-control" ng-model="vm.name" placeholder="Enter name here" required />
<span ng-show="form.name.$dirty && form.name.$error.required" class="help-block">Name is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="text" ng-model="surname" name="text" id="surname" class="form-control" ng-model="vm.surname" placeholder="Enter surname here" required/>
<span ng-show="form.surname.$dirty && form.surname.$error.required" class="help-block">Surname is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" ng-model="vm.email" placeholder="Enter email here" required />
<span ng-show="form.email.$dirty && form.email.$error.required" class="help-block">Email is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="review">Review</label>
<input type="text" name="text" id="review" class="form-control" ng-model="vm.review" placeholder="Enter review here" required/>
<span ng-show="form.review.$dirty && form.review.$error.required" class="help-block">Review is required</span>
</div>
</div>
<div class="form-actions">
<button id="submit" type="submit" onclick="passInfo()" class="btn btn-primary">Submit</button>
<label style="display:none" id="label"><font color="white">Review succesfully created!
<a onclick="refresh()" href="../ang/#!/review">Add new review</a></label> or
View reviews!
</div>
</div>
</form>
<div>
<div ng-init="init()" class="slide-animate-container">
<div class="slide-animate" ng-include="main.view.html"></div>
</div>
</div>
</div>
Currently I add these values to button to test if values are added:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
My main.view is inserted into the review.view (because form and reviews are on the same page, main is for the review listing and reviews are submitted form)
After submiting form all these values appear in the button, but after refreshing page none of them are shown anymore. I kind of understand that it is all because everything I do with local storage is inside submit() function, but I am not sure how to fix it
You can write a init function on second controller and set the local Storage value in a variable.So whenever you refresh the page, init function will be called and local storage value will be available for you to use it in View
see below line:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
"obtained_array" belong to $rootScope, so $rootScope can't bind to the template(binding to $rootScope is not possible )
quick solution is: change the following line
in case of: MainController
$scope.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;
in case of :ReviewController (you are setting in this ctrl "LS_wimmtkey")
$scope.$parent.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;

Blur function not being called

I have the following code for sharing an article by email
function internalLabelBlur(elm) {
if (!elm.value) {
elm.value = elm.defaultValue;
}
if (elm.value == elm.defaultValue) {
elm.className = elm.className.replace("internal-label-emph", "internal-label");
}
} // function internalLabelBlur(elm)
function internalLabelFocus(elm) {
if (elm.value == elm.defaultValue) {
elm.value = "";
}
elm.className = elm.className.replace("internal-label", "internal-label-emph");
} // function internalLabelFocus(elm)
function z_onclick() {
return false;
}
Markup:
<div id="emailErrEmailAddressArrow" class="errorarrow" style="visibility:hidden;">
<img src="~/Content/Images/error_arrow_signup.png" alt="sign up error arrow">
</div>
<input id="txtEmailAddress" name="txtEmailAddress" class="internal-label inputbox"
onfocus="javascript:internalLabelFocus(this);"
onblur="javascript:internalLabelBlur(this);"
onclick="return z_onclick()" type="text" value="E-mail address*" />
The problem is the onblur function not being called. Can anyone help me as to why?

AngularJS : interactive search

I'm new to AngularJS, and, for a project, I need to make an interactive search engine.
So I did this for now :
article/views/articles.html
<form class="form-inline">
<div class="form-group">
<label for="filter-text">Text </label>
<input type="search" class="form-control" id="filter-text" placeholder="Search for text" ng-change="applyFilter();" ng-model="filters.text">
</div>
<div class="form-group">
<label for="filter-date-start">Entre </label>
<input type="date" class="form-control" id="filter-date-start" placeholder="Entre" ng-change="applyFilter();" ng-model="filters.date_start">
</div>
<div class="form-group">
<label for="filter-date-end">Et </label>
<input type="date" class="form-control" id="filter-date-end" placeholder="Et" ng-change="applyFilter();" ng-model="filters.date_end">
</div>
</form>
<div class="hidden-sm hidden-xs col-md-6">
<div
ng-repeat="article in articles"
class="article"
ng-include="'article/views/article.html'" >
</div>
</div>
article/views/article.html
<div ng-hide="article.isHidden">
<!-- My Article DOM -->
</div>
article/article.js
angular
.factory('articleRetriever', function ($http, $q){
this.getLast = function( id ){
var url = 'http://localhost:8080/articles/';
if (id) url += id;
return $http.get(url ,{'Access-Control-Allow-Origin': 'localhost:*'})
.then(function(response) {
var articles = [];
for (var idx in response.data.data) {
var article = response.data.data[idx];
article.isHidden = false;
articles.push(article);
}
return articles;
});
};
return this;
})
.controller('ArticlesCtrl', ['$scope', 'articleRetriever', function($scope, articleRetriever) {
$scope.articles = [];
$scope.filters = { tag: null, date_start : null, date_end : null, text : null };
articleRetriever.getLast()
.then(function(arrItems){
$scope.articlesLoaded = arrItems;
$scope.articles = $scope.articles.concat(arrItems);
});
$scope.applyFilter = function () {
var contains = $scope.filters.text.split(' ');
for (var idx in $scope.articles) {;
$scope.articles[idx].isHidden = true;
if (contains.length > 0) {
for( var jdx in contains) {
if ($scope.articles[idx].body.toUpperCase().indexOf( contains[jdx] ) > -1)
$scope.articles[idx].isHidden = false;
if ($scope.articles[idx].title.toUpperCase().indexOf( contains[jdx] ) > -1)
$scope.articles[idx].isHidden = false;
}
}
}
};
});
But when I fill the input with some text, the modification on $scope.articles didn't hide the article's div in article/views/article.html.
Can someone explain why and could give me a solution ?
Thanks :-)
My bad, the search form wasn't inside the div with the ng-controller="ArticleCtrl" directive, I moved it inside and all works perfectly now.

Categories

Resources