Trigger AngularJS $scope event on key press [duplicate] - javascript

This question already has answers here:
How to use a keypress event in AngularJS?
(19 answers)
Closed 7 years ago.
Is it possible to trigger a $scope function on keypress. I like to know whats the most comfortable way to handle key press in a "form case". I created a dummy plunker.
Controller
// Code goes here
var myApp = angular.module("myApp", []);
//main controller define
myApp.controller('MainCtrl', ['$scope', MainCtrl]);
/**
* MainCtrl object wrapper
*/
function MainCtrl ($scope) {
/**
* Submit function
*/
$scope.submit = function () {
console.log('Submit was triggered');
}
}
View
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<input type="text" placeholder="Trigger on enter key" />
<button ng-click="submit();">Trigger on click</button>
</div>
</body>
</html>

Try wrapping it in a form tag and using ng-submit
<form ng-submit="submit()">
<input type="text" placeholder="Trigger on enter key" />
<button>Trigger on click</button>
</form>

Related

Validate directive elements from a form on the main page

My question is about handling client side validations for a large Angular app. I have a big SPA app with different components which includes reusable components like zip control. Now I can integrate these components in my page form but how can I trigger the validations for elements residing within the components. For e.g. my zip component has city input box, state select box and zip input box, now how can I trigger validations for these components from form submit?
I am using the following solution for my application for now. I am able to validate the required fields with this solution.
I created two input field one from the directive and other within the form. I am able to show error messages for both the fields. Similarly this can be done for some other form of validations.
Here is my plunker
https://plnkr.co/edit/laW9jYoNCszHlPeIl3Vs?p=preview
script.js
var app = angular.module('validationModule', []);
app.controller('mainCtrl', mainCtrl);
app.directive('testDirective', testDirective);
function testDirective(){
var testDirective = {
template: 'First Name: <input type="text" name="fName" required ng-model="user.firstName">'
};
return testDirective;
}
mainCtrl.$inject = ['$scope'];
function mainCtrl($scope){
$scope.submitForm = function(user){
alert(user.firstName + " " + user.lastName);
}
}
Index.html file
<!DOCTYPE html>
<html ng-app="validationModule">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.js" charset="UTF-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-animate.js" charset="UTF-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-sanitize.js" charset="UTF-8"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.1.js" charset="UTF-8"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<form name="myForm" ng-submit="myForm.$valid? submitForm(user) : ''" novalidate>
<h1>Input User Name</h1><br/>
<test-directive></test-directive><br/>
Last Name: <input type="text" name="lName" required ng-model="user.lastName">
<button type="submit" class="btn btn-danger">Submit</button>
<div class="alert alert-danger" ng-show="myForm.$submitted">
<div ng-show="myForm.fName.$error.required">
First Name is required
</div>
<div ng-show="myForm.lName.$error.required">
Last Name is required
</div>
</div>
<br/><br/><br/>
<h1>Is form valid? {{myForm.$valid}}</h1>
</form>
</body>
</html>

Parameter not passed to next page - AngularJS

I want to pass a parameter to the next page onclick of a button.
I have tried as below; on the first page I have a textarea and I want to pass that value to the next page on button click using AngularJS, I have tried as below, but it's not working.
index.html
<!doctype html>
<html ng-app="project">
<head>
<title>Angular: Service example</title>
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script src="sample.js"></script>
</head>
<body>
<div ng-controller="FirstCtrl">
<h2>{{name}}</h2>
<input ng-model="thing.x"/>
</div>
<input type="button" value="send" onclick="send()">
<script>
function send(){
window.location ="second.html";
}
</script>
</body>
</html>
sample.js
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : {
x : 100
}
};
});
function FirstCtrl($scope, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
}
function SecondCtrl($scope, theService) {
$scope.someThing = theService.thing;
$scope.name = "Second Controller!";
}
second.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Passed data</title>
<script src="sample.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div ng-controller="SecondCtrl">
<h2>{{name}}</h2>
<input ng-model="someThing.x"/>
</div>
<br>
</body>
</html>
Please can you help me to figure it out?
First read this https://docs.angularjs.org/guide/$location
Remove send() function
function FirstCtrl($scope, $location, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
$scope.send = function(){
$location.path('/second').search({id: 12});
};
}
<input type="button" value="send" ng-click="send()">
To send the parameter to next page you have to use $location service.
$location.path('/second').search({id: 12});
But again this will not work for you as you are not using AngularJS for routing , you are using JS for that. I suggest following this PhoneCatApp to learn Angular basics

Angular: when using ng-include, number variable become NaN [duplicate]

This question already has answers here:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
(3 answers)
Closed 7 years ago.
I have a problem when i try to fragment my html with ng-include:
This is what my index.html page looks like when it works (prix=price, TVA=tax):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="style.css" />
<title> TVA </title>
</head>
<body>
<div>
<div ng-app="app" ng-controller="appCtrl">
<input ng-model="tva" placeholder="TVA" /><br />
<input ng-model="prix" placeholder="Prix" />
<select ng-model="taxe">
<option>HT</option>
<option>TTC</option>
</select>
<button id="btn" ng-click="calcul()">Calculer</button>
<p>{{ total }}</p>
</div>
</div>
<script src="angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
The script.js :
app = angular.module('app', []);
app.controller('appCtrl', ['$scope', function ($scope) {
$scope.calcul = function() {
if ($scope.taxe == "TTC") {
$scope.total = parseInt($scope.prix) + $scope.prix * $scope.tva /100;
} else if($scope.taxe == "HT") {
$scope.total = 1/(1+$scope.tva/100)*$scope.prix;
}
};
}]);
So this works, the result is an number (the price with or without tax).
When I use the ng-include like this:
<div>
<div ng-app="app" ng-controller="appCtrl">
<div ng-include="'tva.html'"></div>
<input ng-model="prix" placeholder="Prix" />
<select ng-model="taxe">
<option>HT</option>
<option>TTC</option>
</select>
<button id="btn" ng-click="calcul()">Calculer</button>
<p>{{ total }}</p>
</div>
</div>
I only tried to replace the first input with a new HTML page.
The tva.html :
<input ng-model="tva" placeholder="TVA" /><br />
Now the results show "NaN" (I put those codes on a server so that I can check online). Why is this?
#Josh Beam Answered & explained ng-include creates a child scope on creating the DOM. I'd suggest you to use dot rule in angular that will follow prototypal inheritance on that object and you object value will access in child scope.
Now your object structure will changed to $scope.model={}; and this model will have all the input values. like all will become like model.prix, model.taxe & model.tva so that the prototypal inheritance will follow.
Markup
<div ng-app="app" ng-controller="appCtrl">
<div ng-include="'tva.html'"></div>
<br />
<input ng-model="model.prix" placeholder="Prix" />
<select ng-model="model.taxe">
<option>HT</option>
<option>TTC</option>
</select>
<button id="btn" ng-click="calcul()">Calculer</button>
<p>{{ total }}</p>
</div>
Code
app.controller('appCtrl', ['$scope', function ($scope) {
$scope.model = {};
$scope.calcul = function() {
if ($scope.model.taxe == "TTC") {
$scope.total = parseInt($scope.model.prix) + $scope.model.prix * $scope.model.tva /100;
} else if($scope.model.taxe == "HT") {
$scope.total = 1/(1+$scope.model.tva/100)*$scope.model.prix;
}
};
}]);
tva.html
<input ng-model="model.tva" placeholder="TVA" /><br />
Demo Plunkr
Short answer: don't use ng-include in this instance.
Long answer: ng-include creates a new child scope, so ng-model inside the ng-include isn't appCtrl's TVA. I don't see a reason here to use ng-include anyway, your code is fine without it.
So basically you're getting NaN (not a number) because $scope.TVA is never set when using the ng-include... you're attempting to multiply an undefined variable by another number, which returns NaN:
The reason for that is the ng-include creates a new scope under the scope when the HTML was included, but you can access to the parent scope by specifying $parent
<input ng-model="$parent.tva" placeholder="TVA" /><br />
A better approach is give an alias to your controller, so it will be clear semantically to children controllers accessing to a specific parent.
<div ng-app="app" ng-controller="appCtrl as vmMain">
<div ng-include="'tva.html'"></div>
... and in the other file:
<input ng-model="vmMain.tva" placeholder="TVA" /><br />

How to retrieve the ng-model value to a controller in AngularJS

I have a simple view with an input text field in which the user enter his name and a controller must retrieve that value an assign to employeeDescription variable. The problem is that the ng-model value (from the input) doesn't come to the controller, I just tried using $watch like Radim Köhler explains Cannot get model value in controller method in angular js but doesn't work. I just think it must be simple.
Also a just try by retrieving the name variable (ng-model) from the $scope, like $scope.employeeDescription = $scope.name; but doesn't retrieve value and the Google chrome console doesn't give me any output about that. Any solution?
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body ng-app='angularApp'>
<div ng-controller='nameController'>
<div>
Name <input type="text" ng-model='name' />
</div>
Welcome {{employeeDescription}}
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
(function(angular) {
var myAppModule = angular.module('angularApp', []);
myAppModule.controller('nameController', function($scope) {
$scope.employeeDescription = name;
});
})(window.angular);
Your code should fail, cause the 'name' variable in the controller is never defined. You have two variables defined in your code: $scope.employeeDescription and $scope.name (defined in the ng-model of the input). Note that '$scope.name' is being defined, not 'name'.
My suggestion is to leave only one variable:
<div>
Name <input type="text" ng-model='employeeDescription' />
</div>
myAppModule.controller('nameController', function($scope) {
$scope.$watch('employeeDescription', function() {
console.log($scope.employeeDescription);
});
});

What's the Angular way to update the scope?

I have a simple two-way binding setup with angular, and I added a plain javascript function that updates the value based off of the "alt" tag of an image a user clicks on. The problem is that when I hit save, the data doesn't update until I click inside the textbox and add a space. What's the best way to get around this?
http://plnkr.co/edit/j6tPYYUqvRyvfs32mcrW?p=preview
angular.module('copyExample', [])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.master = {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master = angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}
]);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
</head>
<body ng-app="copyExample">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name:
<input type="text" ng-model="user.name" id="name" />
<br />
<img src="http://placehold.it/100&text=John" onclick="changeText(alt)" alt="John" />
<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
function changeText(value) {
document.getElementById('name').value = value
}
</script>
</body>
</html>
working fiddle - http://jsfiddle.net/lwalden/b2p7pu7g/
If you are already using Angular then don't write a plain vanilla javascript function for the image click event - use Angular.
Also it's recommended not to use the alt attribute in this way. You could use a data- attribute instead.
Additional attributes within a tag to pass values to a function

Categories