Ionic Button Click not working - angularjs

My code is pretty simple. Here is an Ionic Screen called Settings which has a thing called Hours Per Week.
<ion-view title="Settings">
<ion-content class="has-header">
<ul class="list">
<label class="item item-input item-label">
<span class="input-label">Hours per week</span>
<input type="text" ng-model="hoursPerWeek" value="37">
</label>
</ul>
<button class="button button-balanced" ng-click="submitClicked()">
Save
</button>
</ion-content>
</ion-view>
This settings screen is using SettingsCtrl, as defined in my app.js file. Here is my controller (Edited):
angular.module('starter.controllers', [])
.controller('SettingsCtrl', function($scope) {
$scope.hoursPerWeek = '37';
$scope.submitClicked = function(){
localStorageService.set('hoursPerWeek',$scope.hoursPerWeek);
console.log("Set Value of hoursPerWeek as : " + $scope.hoursPerWeek);
}
})
As it is evident from above, it uses angular-local-storage module, and I have made sure it is injected into the app as in this declaration :
angular.module('starter', ['ionic', 'starter.controllers', 'LocalStorageModule'])
The problem is submitClicked() does not seem to work. Like if I change the hours per week value to 42 (from 37) , it will seem to work for the current localhost session. When I stop the server and run it again, the value goes back to 37. I dont know whats going wrong here. Any help would be appreciated. I'm facing a new error as described in EDIT 2 below.
EDIT 1 (FIXED):
#icewind, here is the error I am facing
TypeError: localStorage.get is not a function
at new <anonymous> (controllers.js:45)
at Object.instantiate (ionic.bundle.js:18015)
at $controller (ionic.bundle.js:23417)
at Object.self.appendViewElement (ionic.bundle.js:59908)
at Object.render (ionic.bundle.js:57901)
at Object.init (ionic.bundle.js:57821)
at Object.self.render (ionic.bundle.js:59767)
at Object.self.register (ionic.bundle.js:59725)
at updateView (ionic.bundle.js:65400)
at ionic.bundle.js:65377
EDIT 2:
This time I have no errors. I am able to call the submitClicked() from the Save button but the problem now is, the value gets reset back to 37. I've added a console log function in the submitClicked() function as in the edited controller code above.
I'm trying to modify the value of hoursPerWeek by typing in 42, and when I click the Save button, the thing I'm getting on the console is :
Set Value of hoursPerWeek as : 37

You have to use value from localStorage if available
.controller('SettingsCtrl', function($scope, localStorageService) {
$scope.hoursPerWeek = localStorageService.get('hoursPerWeek') || 37;
$scope.submitClicked = function(){
localStorageService.set('hoursPerWeek',$scope.hoursPerWeek);
}
})
And configure your injector to provide it. Otherwise you're just saved it and never used

Here is how I fixed my code. I've made little changes to my HTML. It looks almost similar to the time I asked the question :
<ion-view title="Settings">
<ion-content class="has-header">
<ul class="list">
<label class="item item-input item-label">
<span class="input-label">Hours per week</span>
<input type="text" ng-model="config.hoursPerWeek">
</label>
</ul>
<button class="button button-balanced" ng-click="save()">
Save
</button>
</ion-content>
</ion-view>
Here comes the controller. I've had to make a few changes here. It now looks like this :
.controller('SettingsCtrl' , function($scope, localStorageService) {
$scope.config = {
hoursPerWeek: localStorage.getItem('hoursPerWeek' , 37) || 37
};
$scope.save = function() {
console.log($scope.config.hoursPerWeek);
localStorage.setItem('hoursPerWeek', $scope.config.hoursPerWeek);
};
})
#icewind 's idea actually motivated this answer.
Thanks.

Related

Implementing a script in Ionic Typescript

I would like to implement dynamically added buttons to my Ionic app. I found that I can use the following code for this task.
The first part of the code I placed into the home.html file inside html body.
<div ng-controller="MyCtrl">
<div class="list list-inset">
<div class="item-input" ng-repeat="input in inputs">
<label class="item-input-wrapper">
<input type="text" placeholder="Type something" ng-model="input.value" />
</label>
<button class="button button-small button-balanced" ng-if="$index == inputs.length - 1" ng-click="addInput()">
<i class="icon ion-plus"></i>
</button>
<button class="button button-small button-assertive" ng-if="$index != inputs.length - 1" ng-click="removeInput($index)">
<i class="icon ion-minus"></i>
</button>
</div>
</div>
The second part of the code I placed to the home.ts file. I tried to place this code in the main class.
var app = angular.module('myApp', []);
app.controller("MyCtrl", function($scope) {
$scope.inputs = [{
value: null
}];
$scope.addInput = function() {
console.log("new input");
$scope.inputs.push({
value: null
});
}
$scope.removeInput = function(index) {
$scope.inputs.splice(index, 1);
}
});
Unfortunately, I cannot define a variable:
var app = angular.module('myApp', []);
Because I am getting a "Typescript error". Unfortunately, I don't know how to solve this problem. I hoped that some of you will know a solution and can help me with this problem.
The second part of the code I placed to the home.ts file
This statement suggests that you have created an ionic 2+ project(currently Ionic 3.x). This does not use angularjs (v 1.x) and uses angular 5.x instead.
If you want to start an ionic v1 project,
you need to set the type in your start command.
ionic start myApp blank --type=ionic1
Or you need to read up on latest angular docs here if you need to start an ionic v3 project.

TypeError: Cannot read property 'inputText' of undefined because of naming convention i used like "lunchCtrl.iform.inputText"

I am getting this error when i click the button without entering anything in input field. I am seeing this is because of the naming convention as "lunchCtrl.iform.inputText". when i use this as "lunchCtrl.inputText" or just "inputText" in controller and html its going good without error for empty value onbutton click.
if i enter any text and click the button its going good.
can anyone help me whats going wrong here.
i have attached the code in the following jsfiddle [here][1]. please help me to find the reason.
https://jsfiddle.net/29bmy95j/
code for here:
index.html
Lunch Checker
<div class="form-group">
<input id="lunch-menu" type="text"
placeholder="list comma separated dishes you usually have for lunch"
class="form-control" ng-model="lunchCtrl.iform.inputText">
</div>
<div class="form-group">
<button class="btn btn-default" ng-click="checkTooMuch()">Check If Too Much</button>
</div>
<div class="form-group message">
<!-- Your message can go here. -->
</div>
Entered values::{{lunchCtrl.iform.inputText}}
<p ng-bind="errorMsg" style="color:red"></p>
App.js:
var app=angular.module('LunchCheck', []);
app.controller('LunchCheckController', ["$scope",function($scope){
//function for checkTooMuch() ng-click event
$scope.checkTooMuch=function(){
var inputfieldVal=$scope.lunchCtrl.iform.inputText;
$scope.inputfieldValScope=inputfieldVal;
var array=inputfieldVal.split(',');
//$scope.array=array;
var arrLen=array.length;
if(arrLen > 3){$scope.errorMsg="Too much!";}
else{$scope.errorMsg="Enjoy!";}
}
}]);
error Image
Because $scope.lunchCtrl.iform is not defined, thus initially when you don't type anything in the textfield $scope.lunchCtrl.iform.inputText will trigger an error.
$scope.checkTooMuch=function(){
var inputfieldVal=$scope.lunchCtrl.iform.inputText;//error
So the fix would be to
OPTION 1
write a check and avoid:
$scope.checkTooMuch=function(){
if (!$scope.lunchCtrl.iform.inputText){
return;
}
...your code
OPTION 2
Define your variable like below in the controller
app.controller('LunchCheckController', ["$scope",function($scope){
//var v=$scope.inputText='';
this.iform = {inputText:""};
...
working code here

Reset Angular dropdown option in Ionic - won't reset after value is changed from initial value

I'm trying to figure out why I can't seem to wrangle a simple angular dropdown reset.
When the view loads, you hit the button "Reset", and it changes whatever value is selected to a different one, based on what the functionality in the controller dictates. This works fine on page load, but if you change the value in the dropdown THEN click "Reset", it does nothing. It doesn't reset the dropdown as specified in the function and I can't figure it out.
Steps to reproduce:
Page loads
Click "Reset" button
Dropdown value changes to "Japanese"
Change the value back to "English"
Click "Reset" button
Nothing. It should change the value back to English, but doesn't.
I've boiled everything down to the most basic example using an extremely basic ionic example in my Codepen:
http://codepen.io/starshock/pen/EPdXpz
Basically, here is my controller code:
.controller('DropdownController', [ '$scope', '$state', function($scope, $state) {
$scope.navTitle = 'Dropdown Reset';
$scope.reset = function() {
$scope.selectedOption = $scope.languages[0];
}
$scope.languages = [
{ name: "English"},
{ name: "Japanese"}
];
$scope.selectedOption = $scope.languages[1];
}]);
And here is my template:
<script id="entry.html" type="text/ng-template">
<ion-nav-bar animation="nav-title-slide-ios7"
type="bar-positive"
back-button-type="button-icon"
back-button-icon="ion-ios7-arrow-back">
</ion-nav-bar>
<ion-view title="{{navTitle}}" class="bubble-background">
<ion-content has-header="true" padding="true">
<div class="item item-input item-select" href="#">
<label>
<div class="input-label">
Select language
</div>
<select
data-ng-options="language.name for language in languages"
data-ng-model="selectedOption">
</select>
</label>
</div>
<button class="button button-positive" ng-click="reset()">Reset</button>
</ion-content>
</ion-view>
</script>
I've been struggling with this problem for months and I have a number of instances that utilize similar code. Any Angular masters have any thoughts? :D
You need to change your controller slightly to reference the same object each time (see https://stackoverflow.com/a/17607794/360067 and the answer referenced i.e. https://stackoverflow.com/a/14049482/360067 for the basics).
Assuming the default value you want is English (if it's Japanese, just change the index to 1 in both places)
$scope.reset = function() {
$scope.filter.selectedOption = $scope.languages[0];
}
...
$scope.filter = {
selectedOption: $scope.languages[0]
};
and in your HTML
<select
data-ng-options="language.name for language in languages"
data-ng-model="filter.selectedOption">
</select>
CodePen - http://codepen.io/anon/pen/KVGqOG

Angular PDF viewer: How to use

I need to use a pdf viewer on my web app which is in anugularjs. I found Angular PDF viewer and it's ok for me. But I don't know what code insert to use it.
At the moment I've:
in html:
<div ui-content-for="title">
<span class="small"></span>
</div>
<div class="scrollable">
<div class="scrollable-content">
<div class="list-group">
<site-frame style="display:block; height: 100%;">
<pdf-viewer
delegate-handle="my-pdf-container"
url="pdfUrl"
scale="1"
show-toolbar="true"
headers="{ 'x-you-know-whats-awesome': 'EVERYTHING' }">
</pdf-viewer>
<button class="btn btn-default" ng-click="loadNewFile('position/file.pdf')">Load</button>
</site-frame>
</div>
</div>
</div>
in the controller:
'use strict';
var pdfControllerModule = angular.module('pdfControllerModule', ['ServiceOModule']);
pdfControllerModule.controller('pdfController',
['$scope','pdfDelegate', '$routeParams', 'Service_o', function($scope, pdfDelegate ,$routeParams, Service_o) {
$scope.pdfUrl = 'position/file.pdf';
$scope.loadNewFile = function(url) {
pdfDelegate
.$getByHandle('my-pdf-container')
.load(url);
};
}]);
what is incorrect and what code I insert?
Or If you know the correct code to insert in these two file, do you write me? Thanks Help me
I do not see any problem with the code. Just Make sure you have reference to the pdf.js in your main application module.
angular.module('app',['pdf'])
Also the html needs reference to the the pdf.combined and angular-pdf-viewer js files.

Type error : Cannot read property 'childNodes' of undefined

I am trying to display a modal when the view is loaded.
Code :
//View
<div id="showCom" ng-controller="showmodalCtrl" ng-init="init()">
<div class="modal fade" id="companyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Please Select Company</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label class="control-label">Recipient:</label>
<input type="text" class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
//Controller
.controller('showmodalCtrl', ['$scope', function($scope){
$scope.init = function(){
$('#companyModal').modal("show");
}
}])
Everything works fine and the modal is displayed but I get this error on the console :
Type error : Cannot read property 'childNodes' of undefined
I have no idea why this is happening.
Also if I remove the "form" from the modal , i don't get any error. So I guess the problem is with the form but I am not able to resolve it.
Thanks in advance.
I had the same problem and I managed to resolve it by wrapping the modal open function inside a $timeout() or a normal setTimeout() function.
setTimeout(function(){
jQuery('#messageModal').modal('show');
}, 0);
I had the same error message when trying to use a JQuery plugin. Running it after document ready resolved the issue for me. The plugin was running fine but the angular code that followed in the current scope was not.
It was the "Set timeout"-answer in this thread that led me to try this solution.
Solution for me:
angular.element(document).ready(function () {
//Angular breaks if this is done earlier than document ready.
setupSliderPlugin();
});
As another solution in AngularJS context I'm using this approach:
Include $timeout module in your JS controller
Run init() function with all initializers like this:
$timeout(init, 0);
Works good.
Sorry for edit. Is your HTML well formed? Check that all the tags match.
In your code snippet, it looks like you're missing a closing div. check that - the one that closes the controller div.
I had a similar problem. It would throw an exception when i tried to add some html to dom and compile it using $compile in angularJs.
Inside of the html was another directive that tried to add some dom element from the page to somewhere else in the page.
I just had to call .clone of that element before i moved it to the new location.
And the exception was gone.
$popupContent = $(attrs.popupSelector).clone();
$container = $('<div class="popup-container"></div>');
$container.append($popupContent);
$container.hide();
$('body').append($container);

Resources