I am new to angular.js. I have two directives in my main.js file and every directive has an input text field in the template. There is a Html page (index.html) where I want to use these directive's text fields with another input text field which is a Html input text field.
Now I want whatever input user gives in both the directive's text fields the character count should be calculated and the sum should be printed in the third text field which is a Html text field.
Code is given below:-
Main.js file code :
/// <reference path="angular.min.js" />
var app = angular.module("myApp", []);
app.directive("textbox1", function() {
return {
restrict: 'E',
scope: {
timezone : "#"
},
template: "<div> <input type='text' style='background-color:orange; height=21px; width:151px;' ng-model='txtval1' ng-change='updateval()' />{{txtval1.length}} </div>"
}
});
app.directive("textbox2", function() {
return {
restrict: 'E',
scope: {
timezone: "#"
},
template: "<div> <input type='text' style='background-color:orange; height=21px; width:151px;' ng-model='txtval2' ng-change='updateval()'/>{{txtval2.length}} </div>"
}
});
app.controller("myCtrl", function ($scope) {
$scope.updateval = function () {
console.log($scope.txtval1.value);
$scope.txtThird = ($scope.txtval1.length) + ($scope.txtval2.length);
}
});
HTML Page Code :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div ng-app="myApp">
<textbox1></textbox1>
<textbox2></textbox2>
<br/><br/>
<input type="text" ng-model="txtThird"/>
</div>
<script src="scripts/angular.min.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
You need to do something like this:
var app = angular.module("myApp", []);
app.directive("textbox1", function() {
return {
restrict: 'E',
scope: {
timezone : "#",
updateval: "&updateval"
},
template: "<div> <input type='text' style='background-color:orange; height=21px; width:151px;' ng-model='txtval1' ng-change=\"updateval({inputNr:'1', textval: txtval1})\" />{{txtval1.length}} </div>",
}
});
app.directive("textbox2", function() {
return {
restrict: 'E',
scope: {
timezone: "#",
updateval: "&updateval"
},
template: "<div> <input type='text' style='background-color:orange; height=21px; width:151px;' ng-model='txtval2' ng-change=\"updateval({inputNr:'2', textval: txtval2})\" />{{txtval2.length}} </div>"
}
});
app.controller("myCtrl", function ($scope) {
$scope.inputValues = [
{
input: '1',
value: ''
},
{
input: '2',
value: ''
}
];
$scope.updateval = function (inputNr, txtval) {
var updatedInput = _.find($scope.inputValues, {input: inputNr});
updatedInput.value = txtval;
var lengthSum = 0;
angular.forEach($scope.inputValues, function(inputObj){
lengthSum += inputObj.value.length;
});
console.log(lengthSum);
}
});
Here is working: https://codepen.io/neptune01/pen/bWzLvq
Note that I used lodash.
If I understand you need something this:
//index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<textbox length="length1"></textbox>
<textbox length="length2"></textbox>
<br/><br/>
<input type="text" ng-model="txtThird"/>
<p>Sum = {{length1+length2}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
//script.js
'use strict';
var app = angular.module("myApp", []);
app.directive("textbox", function() {
return {
restrict: 'E',
scope: {
length: '='
},
controller: function($scope){
},
template: "<div> <input type='text' style='background-color:orange; height=21px; width:151px;' ng-model='txtval' ng-change='length = txtval.length'/>{{txtval.length}} </div>"
}
});
app.controller("myCtrl", function ($scope) {
$scope.txtThird = "some text";
$scope.length1 = 0;
$scope.length2 = 0;
$scope.updateval = function () {
console.log($scope.txtval1.value);
$scope.txtThird = ($scope.txtval1.length) + ($scope.txtval2.length);
}
You can try it on plunker: https://plnkr.co/edit/XE6OcQX5GOJIPMcVHWum?p=preview
Related
I am trying to create a custom directive which takes a username as an input. It then validates and checks if the username is available or not. If the username is not available I want to pass some values back to the parent Controller.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>AngularJS Isolate Scope</title>
</head>
<body>
<div ng-app="mainApp">
<div ng-controller="AppCtrl">
<div> From Controller : <input type="text" ng-model="ctrlRole"></div><br>
{{parentVariable}}
<input type="text" is-unique="{url: 'http://WWW.GOOGLE.COM'}" ng-model="role"/>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
var app = angular.module('mainApp', []);
app.controller("AppCtrl", function($scope){
$scope.ctrlRole = "Development";
$scope.parentVariable = "a";
});
app.directive("isUnique", function() {
return {
restrict : 'A',
require : 'ngModel',
transclude: 'true',
scope:{
parentVariable:"="
},
link : function(scope, element, attrs, ngModel) {
element.bind('blur', function (e) {
if (!ngModel || !element.val()) return;
var keyProperty = scope.$eval(attrs.isUnique);
console.log('this is the keyProperty we have received from the front end ' + keyProperty.url);
var currentValue = element.val();
console.log('this is the data we are going to validate ' + currentValue);
if(currentValue == 'AE'){
console.log('Changing the value ');
scope.parentVariable = 'b';
}
});
}
}
});
</script>
</body>
In summary I am trying to change the value of parentVariable from the directive scope depending on some conditions but its not happening, please let me know what I am doing wrong.
You specify the isolate scope parameter parentVariable, but in the template there is no value passed to it:
<input type="text" is-unique="{url: 'http://WWW.GOOGLE.COM'}" ng-model="role"/>
You would need:
<input type="text" is-unique="{url: 'http://WWW.GOOGLE.COM'}" parent-variable="parentVariable" ng-model="role"/>
Here, is an isolated example.
var app = angular.module('test', []);
app.controller('MainCtrl', function($scope) {
$scope.foo = 'foo';
});
app.directive('testDir', function($timeout) {
return {
restrict: 'A',
scope: {
val: '='
},
link: function(scope) {
console.log(scope.val);
$timeout(function() {
scope.val = 'bar';
}, 1000);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test">
<div ng-controller="MainCtrl">
{{foo}}
<div test-dir val="foo"></div>
</div>
</div>
I wan to use ng-autocomplete with firebase have a look of my html
<!DOCTYPE html>
<html ng-app="Test">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css"href="style.css">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="script.js"></script>
<script src="ngAutocomplete.js"></script>
</head>
<body>
<div ng-controller="TestCtrl">
<form id="form" role="form">
<div class="form-group move-down">
<label for="Autocomplete">Generic Autocomplete</label>
<input type="text" id="Autocomplete" class="form-control" ng-autocomplete="result1" details="details1" options="options1"/>
</div>
<div>result: {{result}}</div>
</form>
</div>
</body>
</html>
and this is my script.js
angular.module( "Test", ['ngAutocomplete'])
.controller("TestCtrl",function ($scope) {
$scope.result1 = '';
$scope.options1 = null;
$scope.details1 = '';
});
and this is ngAutocomplete.js
angular.module( "ngAutocomplete", [])
.directive('ngAutocomplete', function($parse) {
return {
scope: {
details: '=',
ngAutocomplete: '=',
options: '='
},
link: function(scope, element, attrs, model) {
//options for autocomplete
var opts
//convert options provided to opts
var initOpts = function() {
opts = {}
//if (scope.options) {
/*if (scope.options.types) {
opts.types = []
opts.types.push(scope.options.types)
}*/
// }
}
initOpts()
//create new autocomplete
//reinitializes on every change of the options provided
var newAutocomplete = function() {
scope.gPlace = new google.maps.places.Autocomplete(element[0], opts);
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
scope.$apply(function() {
if (scope.details) {
scope.details = scope.gPlace.getPlace();
}
scope.ngAutocomplete = element.val();
});
})
}
newAutocomplete()
//watch options provided to directive
scope.watchOptions = function () {
return scope.options
};
scope.$watch(scope.watchOptions, function () {
initOpts()
newAutocomplete()
element[0].value = '';
scope.ngAutocomplete = element.val();
}, true);
}
};
});
I want to use firebase autocomplete or array of city instead of google map API. So could you please give me idea how I can use it.
Instead of this
<input type="text" id="Autocomplete" class="form-control" ng-autocomplete="result1" details="details1" options="options1"/>
it should be
<input type="text" id="Autocomplete" class="form-control" ng-autocomplete ng-model="result1" details="details1" options="options1" />
Please find working plunker here
see documentation of ngAutocomplete here
I have this piece of code , but when the user writes the color in the input, the background color of the new element is suposed to change but is not working, what am I doing wrong?
<div ng-app="mainApp" ng-controller="MainCtrl">
<input type="text" ng-model="color" placeholder="Enter a color" />
<hello-world/>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: true,
template: '<p style="background-color:{{color}}">Hello World',
link: function(scope, elem, attrs) {
elem.bind('click', function() {
elem.css('background-color', 'white');
scope.$apply(function() {
scope.color = "white";
});
});
elem.bind('mouseover', function() {
elem.css('cursor', 'pointer');
});
}
};
});
</script>
Close your template tag and delete the inline style from there.
Also you should use elem.on() instead elem.bind()
var mainApp = angular.module("mainApp", []);
mainApp.directive('helloWorld', function() {
return {
restrict: 'AE',
template: '<input type="text" placeholder="Enter a color" ng-model="color"/><p>Hello World</p>',
link: function(scope, elem, attrs) {
scope.color = elem.find('input').val();
scope.$watch('color', function(newVal, oldVal){
if(oldVal === newVal) return;
elem.find('p').addClass(scope.color +'');
});
elem.on('mouseover', function() {
elem.find('input').css('cursor', 'pointer');
});
}
};
});
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<!doctype html>
<html ng-app="mainApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<hello-world></hello-world>
</body>
</html>
Please for the example type 'red' or 'blue'.
Hi i am working on custom directives of angularjs. I just want to know that how to call the directive when I click the button. Please suggested me how to achieve this.
Thanks
<div ng-controller="ctrl">
<mydirc></mydirc>
<button ng-click="clickMe()">call clickMe()</button>
</div>
app.directive('mydirc', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function($scope, element, attrs) {
$scope.clickMe= function() {
alert('inside click');
}
}
}
});
The following example shows a sample custom directive which can handle click events; This is a scope-independent directive. And the appRoot module has to be defined earlier.
<div ng-controller="MyController">
<button custom-click="">Click Me</button>
</div>
appRoot.directive('customClick', function() {
return {
link: function(scope, element, attrs) {
element.click(function(){
//Do something useful
});
}
}
});
By "calling" the directive I am going to assume you mean handling the onclick event from the directive.
You can leverage the 'link' property of directives to attach scope initialization and functions like so:
http://jsbin.com/moruyoso/2
HTML
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div clicker></div>
</body>
</html>
JS
var app = angular.module('app', []);
app.directive('clicker', function(){
var link = function(scope){
scope.showMessage = function(){
alert('you clicked the directive!');
};
};
return{
link: link,
template: "<button ng-click='showMessage()'>Click me!</button>"
};
});
This example shows how to handle a click event for more than one button inside a directive:
Java Script: ( app.js )
angular.module('app', [])
.controller("articles.controller", function(){
var viewModel = this;
viewModel.articles =
[
{
title: "PHP",
content: "content 1",
selected: false
},
{
title: "C#",
content: "content 2",
selected: false
}
];
viewModel.addArticle = function(){
viewModel.articles.push(
{
title: "MySQL",
content: "new content",
selected: false
}
);
};
viewModel.select = function(article){
article.selected = !article.selected;
};
viewModel.getAll = function(){
console.clear();
console.log(viewModel.articles);
};
viewModel.getSelected = function(){
console.clear();
angular.forEach(viewModel.articles, function(article, key){
if(article.selected)
{
console.log(article.title);
}
});
};
})
.directive("artilceTile", function(){
return {
restrict: 'E',
scope: {
article: '='
},
link: function(scope, element, attr)
{
scope.displayTitle = function()
{
alert(scope.article.title);
},
scope.displayContent = function()
{
alert(scope.article.content);
},
scope.inverseArticleStatus = function()
{
scope.article.selected = !scope.article.selected;
}
},
template: `
<h1>{{article.title}}</h1>
<p>{{article.content}}</p>
<p ng-if="article.selected">Selected</p>
<input ng-model=article.title>
<button ng-click="displayTitle()">Dispaly Title</button>
<button ng-click="displayContent()">Display Content</button>
<button ng-click="inverseArticleStatus()" ng-if="!article.selected">Select</button>
<button ng-click="inverseArticleStatus()" ng-if="article.selected">Unselect</button>
<br><br><br><hr>
`
};
});
HTML: ( index.html )
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
</head>
<body>
<div ng-controller="articles.controller as articlesController">
<span ng-repeat="article in articlesController.articles">
<artilce-tile article="article"></artilce-tile>
</span>
<br><br>
<button ng-click="articlesController.addArticle()">Add New Article</button>
<button ng-click="articlesController.getSelected()">Get Selected Articles</button>
<button ng-click="articlesController.getAll()">Get All Articles</button>
</div>
<script type="text/javascript" src="angular.js"></script>
<script src="app.js"></script>
</body>
If you mean to ask how to show a directive template on button click, use a variable in the controller scope to show/hide it and update the variable on button click.
<div ng-controller="ctrl">
<mydirc ng-show="showMydirc"></mydirc>
<button ng-click="clickMe()">call clickMe()</button>
</div>
app.controller("ctrl", function($scope){
$scope.showMydirc=false;
$scope.clickMe = function(){
$scope.showMydirc = true;
}
});
Trying to get my head around AngularJS directives. I need to pass a full object from my main controller to the directive. See the code below and jsfiddle: http://jsfiddle.net/graphicsxp/Z5MBf/4/
<body ng-app="myApp">
<div ng-controller="MandatCtrl">
<div person myPerson="mandat.person"></div>
<span>{{mandat.rum}}</span>
<span>{{mandat.person.firstname}}</span>
</div>
and the script:
var myApp = angular.module("myApp", []);
myApp.controller("MandatCtrl", function ($scope) {
$scope.mandat = { rum: "15000", person: { id: 1408, firstname: "sam" } };
});
myApp.directive("person", function () {
return {
scope: {
myPerson: "="
},
template: 'test: <div ng-model="myPerson"><input type="text" ng-model="firstname" /></div>'
}
});
Ok, the binding is working fine for mandat.rum and mandat.person.firstname.
However, I'm trying to pass mandat.person to the directive, and it does not work. I know I must be doing something wrong, the question is what ? :)
Pls see below working copy
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<span>{{mandat.rum}}</span>
<span>{{mandat.person.firstname}}</span>
<input type="text" ng-model="mandat.person.firstname" />
<my-directive mandateperson="mandat.person" >
</my-directive>
<script type="text/javascript">
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope) {
$scope.mandat = { name: "John", surname: "Doe", person: { id: 1408, firstname: "sam" } };
});
app.directive('myDirective', function () {
return {
restrict: 'E',
template: "<div><span>{{mandateperson.id}}<span><input type='text' ng-model='mandateperson.firstname' /></div>",
replace: true,
scope: { mandateperson: '=' }
}
}
)
</script>
</body>
</html>