I'm trying to get started learning AngularJS for an Ionic app I'm working on, and I'm having a little trouble understanding AngularJS having had most previous experience on jQuery which focuses on DOM manipulation rather than frameworking.
If I have the following markup:
<label class="item-input-wrapper">
<i class="icon ion-ios7-chatbubble placeholder-icon"></i>
<input type="text" placeholder="Send a message...">
</label>
<button class="button button-clear button-positive">
Send
</button>
How can I pass the value of the input on to the controller when enter or send is clicked? I'm working on a chat app, so I believe that a model approach is needed so that the message thread can be automatically updated but other than that I have no idea.
Could someone help me out or at least point me in the right direction?
There are several ways to pass value to your controller. Here is the simplest example. As Justin said, you should look into angular basics.
HTML:
<div ng-controller="MyCtrl">
<input type="text" ng-model="foo" placeholder="Enter something" />
<input type="button" ng-click="doSomething()" value="Send" ng-disabled="foo == null" />
</div>
JS:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.foo = null;
$scope.doSomething = function () {
alert("Hello, " + $scope.foo);
}
}
Here is the working fiddle
And I would recommend you to go through this post.
The following markup you posted is the view. What you'll need to do is write a separate JS script called a controller that gets linked to the view. Look into basic Angular tutorials on how to do that and mainly look into how $scope works in Angular.
Your controller will have a function...say:
$scope.foo = function(input) { alert(input); };
From the view, you can pass a value onto the controller with Angular functions such as ng-click.
<a ng-click="foo('this string will be passed in as the text of the alert')">click me</a>
Related
I am looking for a solution on passing data from a specific input text field to AngularJS. it may be a Javascript variable too. If the variable is changed from inside a javascript code it is not updating on AngularJS side. If i take the same variable and in the text field add at least one character or modify something i see variable updating and everything working as it should.
I tried something with angular.element(document.getElementById('ControllerElementID')).scope().funct(); but still no luck. When i update at least one field from the keyboard, all text fields that are related to "ng-model="sig.sigBase6422"" are updating properly as it should. If i call this updates through a JavaScript function i see updates only on specific text field and no updates at all on ng-model happening. How to make it updating as simple as possible? Below i will post a small example. I was able to store data from variable to a external file and in AngularJS read it from file and use it. this is way too long, complicated and ridiculous. I am sure there should be a better way.
Thank you!
<script type="text/javascript">
function addtext1() {document.getElementById("myID1").value = "1111111111111111";}
function addtext2() {document.getElementById("myID2").value = "2222222222222222";}
</script>
<div>
<form action="#" name="FORM1">
<TEXTAREA NAME="sigData" ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" ><br>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" ><br>
<p>Value {{sig.sigBase6422}}!</p>
</div>
<!-- test field -->
Add text 1
Add text 2
Indeed if you want to use AngularJS for what it was created, you have to rewrite your code completely using directive or controller. You variables and functions accessible from the view should be attached to the $scope too.
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope){
$scope.addtext1 = function () {
$scope.sig.sigBase6422 += "1111111111111111";
};
$scope.addtext2 = function () {
$scope.sig.sigBase6422 += "2222222222222222";
};
$scope.sig = {
sigBase6422: ""
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form action="#" name="FORM1">
<TEXTAREA ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br/>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" /><br/>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" /><br/>
<p>Value {{sig.sigBase6422}}!</p>
<!-- test field -->
<button ng-click="addtext1()">Add text 1</button>
<button ng-click="addtext2()">Add text 2</button>
</div>
You seem to have misunderstood how angular works. What you're trying to do is not how angular works. What you're trying to do with native JavaScript can be done with angular. Angular can update dom and Dom updates angular as it's responsible for causing updates.... anyway without getting any deeper. You need to read more on how angular works and try sticl within the bounds of angular instead of mixing.
That being said :
Tigger change on the Dom element after you have updated its value. Or better yet get access to scope variable on the Dom and call a function in angular with the value you're and set they value from inside of a angular.
Use this code while updating the value.
pick the controller first using
var scope = angular.element(document.getElementById('yourControllerElementID')).scope();
scope.<variablename> = <your operation>;
then
scope.$apply();
the remaining thing will be taken care by Angular.
My ng-model is value not updating in controller bonded with $scope. There is no syntax error in my code that I can assure. Only one controller bonded with html.
$watch is only running once when page is loaded.
Note that I have 220 around total watchers in my file and controller file is very big like 1500+ lines of code. To cross check I also bind one div with different controller and it is working as expected both $watch and $scope.
I have verified that my variable is not having duplicate name in entire project. I think angular gives no performance issue till 2000 watchers per page. But here that is not the case. Can someone please shed some light on this strange behavior. Any help would be appreciated.
Note: I am not posting code here as it was working fine when I started working on controller initially and on separate prototype also code works well. This behavior has been introduced recently with more and more code.
HTML file:
<div id="studentSearch" class="form-group__text row studentmargin">
<input id="search" type="text" class="studentSearch" tabindex="2"
ng-keyup="$event.which === 13 && !disableSearch ? clickSearchButton(): ''"
placeholder="Search by Name or Email"
ng-model="searchString">
<label for="search">
<button type="button" class="link" tabindex="3"
ng-click="clickSearchButton()" ng-if="!searchResultFlag"
ng-disabled="disableSearch">
<span class="icon-search"></span>
</button>
</label>
<button type="button" class="link" ng-click="clearStudentsSearch()"
ng-if="searchResultFlag" tabindex="4">
<span class="icon-close"></span>
</button>
Controller:
angular.module('app.pages.course.details').controller("CourseDetailController", ['$scope', function($scope){
$scope.disableSearch = true;
$scope.$watch('searchString', function(oldValue, newValue){
if(newValue.length >= 3) {
$scope.disableSearch = false;
}
});
$scope.clickSearchButton = function() { /* Search logic */ }
$scope.clearStudentsSearch = function() {
$scope.searchString = "";
} }]);
So the logic is search icon will only get enabled once the searchString is greater than or equal to 3 letters. On clearing search button it gets cleared from UI and if we print the scope it has that value, Because of that on ENTER press, search work again.
Could you try using parent with the model ng-model="parent.name".
I have got a form where user will enter a name and click Next. What I want to do is that, when the user clicks Next, I want to alert the updated value of $scope.name inside toChat function, but initial value is alerted, which is James. How can I access the updated value inside angular function? I have some serious problems understanding sharing variables within AngularJs.
js
.controller('NewcontactCtrl', function($scope,$rootScope, $ionicHistory,$window) {
$scope.name='James';
$scope.myGoBack = function() {
$ionicHistory.goBack();
};
$scope.toChat = function() {
alert($scope.name);
};
})
html
<ion-view view-title="New contact">
<ion-nav-back-button>
</ion-nav-back-button>
<ion-nav-buttons side="primary">
<button class="button" ng-click="myGoBack()">
Cancel
</button>
</ion-nav-buttons>
<ion-nav-buttons side="secondary">
<button class="button" ng-click="toChat()" >
Next
</button>
</ion-nav-buttons>
<ion-content scroll="false" has-header="false" padding="true" >
<div class="list">
<label class="item item-input">
<input type="text" placeholder="Name" ng-model="name" />
</label>
<label class="item item-input">
<textarea placeholder="Notes" ng-model="notes" rows="10"></textarea>
</label>
</div>
</ion-content>
</ion-view>
Can anyone help ?
Please see: https://github.com/angular/angular.js/wiki/Understanding-Scopes
The most relevant part in the above:
Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope. It doesn't work the way most people expect it should work. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works. New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view and ng-include all create new child scopes, so the problem often shows up when these directives are involved. ...
This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.
Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
<input type="text" ng-model="someObj.prop1"> rather than
<input type="text" ng-model="prop1">.
I believe you have a directive in there somewhere (probably ion-content) that is creating a new scope where your input field is, separated from the scope where your Next button is.
To simulate this, I've used ng-repeat in the below snippet (but I'm repeating only once), which causes the same behaviour of splitting the scopes. If you were to use your controller code unmodified with this html, you'd reproduce the issue you're experiencing.
The solution around this is to 'use a dot (.)' when binding. Notice that I've wrapped the name within an object called 'data' on the scope, so now you refer to this as data.name instead of just name.
(function() {
'use strict';
angular.module('myApp', [])
.controller('NewcontactCtrl', function($scope, $window) {
$scope.repeaterTest = [1];
$scope.data = {name: 'James'};
$scope.toChat = function() {
$window.alert($scope.data.name);
};
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="NewcontactCtrl">
<label ng-repeat="test in repeaterTest">
<input type="text" placeholder="Name" ng-model="data.name" />
</label>
<button class="button" ng-click="toChat()">
Next
</button>
</div>
</div>
I think you need to alert something similar to...
alert($scope.name)
Addition to #Paul Fitzgerald, points, ensure that ng-controller="NewcontactCtrl" is included at the top scope in HTML DOM.
try adding a service in order to share data within scopes
.controller('NewcontactCtrl', function($scope,$rootScope,sharedData $ionicHistory,$window) {
$scope.name=sharedData.Name ;
$scope.myGoBack = function() {
$ionicHistory.goBack();
};
$scope.toChat = function() {
alert(sharedData.Name);
};
});
app.factory('sharedData', [function () {
var self = {};
self.Name = "James";
return self;
}]);
I am new to AngularJS and would like to create functionality for a login page similar to what you find here when you click the 'Forgot Password' link:
http://bootsnipp.com/snippets/featured/login-amp-password-reminder#comments
Is it best to use a directive, since this is behavioral, instead of a controller? I've tried quite a bit with creating a controller for it, but as I search for help on the subject I find that using a controller for this may not be the way to go. Here was my latest trials which was unsuccessful (the link does nothing when clicked):
on controller side in a js file:
angular.module('mean.users')
.controller('SwitcherCtrl', ['$document',
function($document) {
$document.ready(function () {
$document.getElementById('olvidado').click(function (e) {
e.preventDefault();
$document.getElementById('form-olvidado').toggle('500');
});
$document.getElementById('acceso').click(function (e) {
e.preventDefault();
$document.getElementById('form-olvidado').toggle('500');
});
});
}
])
on html side, I included ng-controller="SwitcherCtrl" where necessary.
JQuery approach is completely incompatible with AngularJS. DOM Manipulation is only allowed in directives in the link function otherwise it is a very bad practice. Try to start from scratch and forget about JQuery. The magic of AngularJS happens with 2-way bindings.
You could use a directive, with a login controller and a factory/service to hold the username and password and send it to the database. For this login there is definitely no need for JQuery at all. You can check this question here:
AngularJS- Login and Authentication in each route and controller
edit: In your question above, it is not a directive instead of a controller. A directive can have a controller that is applied to a specific scope. You could do the same thing with both but depends how many times you will reuse this login snippet - I guess you won't need it but I believe it is still good practice to make one.
edit 2: if you havent' read this one, please do it! I believe you will answer most of your questions about the two different (opposite I would say) technologies. "Thinking in AngularJS" if I have a jQuery background?
Also since I came from Jquery background too, I followed these four resources in order and now I can make most of the things I want:
Introduction to Angular.js in 50 Examples (part 1) https://www.youtube.com/watch?v=TRrL5j3MIvo
Introduction to Angular.js in 50 Examples (part 2) https://www.youtube.com/watch?v=6J08m1H2BME
Free Interactive AngularJS learning for Beginners https://www.codeschool.com/courses/shaping-up-with-angular-js
More AngularJS resources by topic egghead.io https://egghead.io/technologies/angularjs
edit 3: Since I saw good interest in my answer I decided to expand it with what to avoid/best practices so the code is more testable, maintainable and easier to migrate to Angular 2:
5 Guidelines For Avoiding Scope Soup in Angular
http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html
No $scope soup, bindToController in AngularJS
https://toddmotto.com/no-scope-soup-bind-to-controller-angularjs/
Angular JS - you probably shouldn't use $watch in your controllers.
http://www.benlesh.com/2013/10/title.html
11 Tips to Improve AngularJS Performance
http://www.alexkras.com/11-tips-to-improve-angularjs-performance/
You can try this out, it uses directives and html. Whether the login or forgot username shows is tied to the state of a scope variable in the directives link function.
Fiddle
<div ng-app="myApp">
<div my-auth>
<div ng-show="active">
<form name="login">
<input type="email" ng-model="email" placeholder="your#email.com" required />
<input type="password" ng-model="passwd" required />
<button ng-disabled="!login.$valid">Login</button>
</form>
forgot password?
</div>
<div ng-show="!active">
<form name="forgot">
<input type="email" ng-model="email" placeholder="your#email.com" required />
<button ng-disabled="!forgot.$valid">Reset Password</button>
</form>
access
</div>
</div>
</div>
The directive
angular.module('myApp', [])
.directive('myAuth', function(){
return {
link: function(scope, elem, attr){
scope.active = true;
scope.toggle = function(){
scope.active = !scope.active;
};
}
};
});
Thanks to everyone who answered. They kicked off this thing moving in the right direction and I was able to improve upon it to come to the exact answer shown below.
The HTML:
<div ng-controller="SwitcherCtrl">
<div data-fold-toggle="active">
<form id="login">
<input type="email" ng-model="email" required="">
<input type="password" ng-model="password" required="">
<button type="submit">Login</button>
<a ng-click="active=!active">Forgot your password?</a>
</form>
</div>
<div data-fold-toggle="active" style="display: none;">
<form id="forgotpw">
<input type="email" ng-model="email" required="">
<button type="submit">Reset Password</button>
<a ng-click="active=!active">Account Access</a>
</form>
</div>
</div>
The Controller & Directive:
.controller('SwitcherCtrl', function($scope) {
$scope.active = true;
})
.directive('foldToggle', function() {
return {
restrict: 'A',
scope:{
isOpen: '=foldToggle'
},
link: function(scope, element) {
scope.$watch('isOpen', function(newVal,oldVal){
if(newVal !== oldVal){
element.toggle(200);
}
});
}
};
});
I was using ng-include on a few of my pages, however I had to stop using ng-include because it was breaking the angular-ui datepicker. I opened this Github bug.
I am wondering if anyone else was having issues with directives not functioning the same way when being used as part of a ng-include.
Is there a way to make the datepicker work as expected as part of a ng-include?
Here is a plunker showing how it is broken. http://plnkr.co/edit/AboEJGxAK3Uz76CfpaZ0?p=preview
Here is the html that works when on the view, but does not work when part of a ng include.
<div class="row">
<div class="col-md-2">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="yyyy/MM/dd" ng-model="something.dt2" is-open="secondCal"
min-date="minDate" name="secondCal" max-date="'2015-06-22'" datepicker-options="dateOptions"
date-disabled="disabled(date, mode)" ng-required="true" close-text="Close"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" style="line-height: 1.2em" ng-click="open($event, 'secondCal')">
<i class="ss-icon ss-calendar"></i>
</button>
</span>
</p>
</div>
</div>
Here is the JS from the controller.
$scope.open = function ($event, elementOpened) {
$event.preventDefault();
$event.stopPropagation();
$scope[elementOpened] = !$scope[elementOpened];
};
And two ways I was doing ng-include
<div ng-include src="'dist/partials/myPartial.html'"></div>
<div ng-include="'dist/partials/myPartial.html'"></div>
Update
I found that this is because the ng-include directive creates a new scope for each include. This SO post creates a new directive that does the include without creating a new scope. However there seems there "should" be a way to fix it without using a different include.
The datepicker will be unable to open as soon as the is-open is changed by the datepicker directive itself (e.g. click outside to close the datepicker).
This is a common issue regarding the "Prototypal Inheritance" characteristic of scope.
For a complete detail, you could read this: Understanding-Scopes
You could easily solve this by not storing any primitive values directly into $scope, but some object and using dot-notation like this:
<input type="text" class="form-control"
datepicker-popup="yyyy/MM/dd" ng-model="something.dt2"
is-open="model.secondCal"
and in your controller:
app.controller('MainCtrl', function($scope) {
$scope.model = {};
$scope.open = function($event, elementOpened) {
$event.preventDefault();
$event.stopPropagation();
$scope.model[elementOpened] = !$scope.model[elementOpened];
};
});
Example Plunker: http://plnkr.co/edit/dJNIwSz2Uot3McmIMhd4?p=preview
I've created Plunker to debug it but it works fine with your code
http://plnkr.co/edit/nxYCiwRqdWMOkfZoRhGY?p=preview
<body ng-controller="MainCtrl">
<div ng-include="'partial.html'"></div>
</body>
after clarification and further tests i see that calendar with ng-include lose the scope when triggering the change not by scope method, the easy workaround would be as per this plunker
http://plnkr.co/edit/nxYCiwRqdWMOkfZoRhGY?p=preview
Don't remember which one of the angular team said it but if you don't have a dot in your model you are doing it wrong.
a little explanation why it works:
if you do
$scope.valueName = value
it will assign value to the current scope immediately
but if you do
$scope.something.valueName = value
what will happen is that angular will first locate $scope.something, if it doesn't exists on current scope it will look in parent (as long as you don't work in isolated scope)
then when it finds it it will assign value or return something like 'cant find valueName of undefined'
from the angularjs documentation:
https://docs.angularjs.org/api/ng/directive/ngInclude
This directive creates new scope.
This directive executes at priority level 400.