I am fairly new with AngularJS. I'm trying to do something simple for the moment. I created a table with some text I'll have to search with, a reset button (In my program is called "Pulisci") and some panels I'll have to use later. The problem is that, if I call the function I created for resetting the page, the panels mysteriously stop working. I'm banging my head on this since last week.
HTML
<!DOCTYPE html>
<html ng-app="sbi">
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<style>
table,
td {
border-width: 2px;
border-collapse: collapse;
padding: 15px;
color: #000000;
text-align: center;
}
table.pos_fixed1 {
position: relative;
top: 30px;
left: 10px;
}
</style>
</head>
<body>
<form name="form">
<table summary="" width="10%" class="pos_fixed1" align="center">
<tr>
<td>Code Subinstaller<br><input name="codeSub" type="text" ng-model="codeSub"></td>
<td>Stato<br>
<select>
<option value="1">...</option>
<option value="2">WHITE LIST</option>
<option value="3">GRAY LIST</option>
</select>
</td>
</tr>
<tr>
<td>Nome Sub Installer<input name="nomeSub" type="text" ng-model="nomeSub"></td>
<td>Cognome Sub Installer<input name="cognSub" type="text" ng-model="cognSub"></td>
<td>Codice Fiscale<input name="codFisc" type="text" ng- model="codFisc"> </td>
</tr>
</table><br>
<button class="btn btn-wide btn-default.active.focus" data-ng- click="">Cerca</button>
<button class="btn btn-wide btn-default.active.focus" data-ng- click="reset()">Pulisci</button>
</form><br><br>
<section ng-controller="PanelController as panel">
<ul class="nav nav-pills">
<li ng-class="{ active:panel.isSelected(1) }"> <a href ng- click="panel.selectTab(1)">Description</a></li>
<li ng-class="{ active:panel.isSelected(2) }"> <a href ng- click="panel.selectTab(2)">Specifications</a></li>
<li ng-class="{ active:panel.isSelected(3) }"> <a href ng- click="panel.selectTab(3)">Reviews</a></li>
</ul>
<div class="panel" ng-show="panel.isSelected(1)">
<h4>Description </h4>
<p>wtf</p>
</div>
<div class="panel" ng-show="panel.isSelected(2)">
<h4>Idk</h4>
<p>Idc</p>
</div>
<div class="panel" ng-show="panel.isSelected(3)">
<h4>APPARI</h4>
<p>???</p>
</div>
</section>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="myapp.js"></script>
</body>
</html>
JS
(function() {
var app = angular.module('sbi', []);
app.controller('PanelController', function() {
this.tab = 1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
});
})();
(function($scope) {
var app = angular.module('sbi', []);
function MyCtrl($scope) {
$scope.reset = function() {
$scope.requiredField = '';
};
};
});
How can I make the Reset() and the panels work simultaneously?
You have re-initialized your angular module.
Initializing your angular module
var app = angular.module('sbi', []);
Second argument in angular.module() is for injecting the required dependency for the module. And hence should be done only once.
In your code, you have again initialized your module.
(function () {
//initialization
var app = angular.module('sbi', []);
app.controller('PanelController', function () {
this.tab = 1;
this.selectTab = function (setTab) {
this.tab = setTab;
};
this.isSelected = function (checkTab) {
return this.tab === checkTab;
};
});
})();
(function ($scope) {
//edit in your code
//re-using the already initialized module
var app = angular.module('sbi');
function MyCtrl($scope) {
$scope.reset = function () {
$scope.requiredField = '';
};
};
});
You should not pass the second argument as parameter.
Reusing your angular module
var app = angular.module('sbi');
EDIT :
Try the following code :
(function () {
var app = angular.module('sbi', []);
app.controller('PanelController', ['$scope', function($scope) {
$scope.tab = 1;
$scope.selectTab = function (setTab) {
$scope.tab = setTab;
};
$scope.isSelected = function (checkTab) {
return $scope.tab === checkTab;
};
$scope.reset = function () {
$scope.requiredField = '';
};
}]);
})();
There is something you are clearly missing here: your reset function is attached to... nothing.
The MyCtrl function is never called (from what we've seen), and the $scope variable is not injected the Angular-way. Actually, nothing here is in the Angular way. Let me try to adjust this so you understand what you should aim for.
First of all, as #Akshay mentioned, there is a huge difference between angular.module('something', []) and angular.module('something'), but they already pointed that out in their response.
Then, your MyCtrl hasn't been registered as a controller in Angular. You just defined the function, you were missing these lines:
var app = angular.module('sbi');
function MyCtrl($scope) {
$scope.reset = function () {
$scope.requiredField = '';
};
};
// This controller will be known as 'MyCtrl'
app.controller('MyCtrl', MyCtrl);
This should work. Note that you won't be needing the surrounding (function ($scope) {...}) as it won't be executed correctly.
Then, you will have to tell Angular to use that controller in that specific part of your page:
<!-- Adding the ng-controller directive here -->
<form name="form" ng-controller="MyCtrl">
...
<button class="btn btn-wide btn-default.active.focus" data-ng-click="reset()">Pulisci</button>
</form>
Then, you will be able to handle your requiredField variable as you wish.
Related
I am trying to make a table cell clickable. When the cell is clicked it will switch the contents from one cell to another. I want to make a basic chess game out of this click action by eventually using angular.element to get the clicked elements and setting the second clicked square equal to the first clicked.html(). Is this possible in AngluarJs using a MEAN somehow?
My current code looks like this but the table cell isn't changing or doing anything when I click.
app.controller('ChessCtrl' , ['$http', '$scope', '$document', function
ChessCtrl($http, $scope, $document) {
var vm = this;
vm.test1 = angular.element(document.getElementById("A1"));
vm.test2 = "";
vm.test3 = "This is a test";
$scope.click = function() {
var temp = vm.test3;
vm.test2 = temp;
vm.test3 = "";
}
}]);
<div ng-Controller="ChessCtrl">
<div class="content">
<div class="left">
<table style="width: 75%">
<tr>
<td id="A1" ><a ng-bind="vm.test3" ng-click="click()"></a></td>
<td class="grey" ng-bind="vm.test2"><a ng-bind="vm.test2" ng-click="click()"></a>
</td>
<td>
</tr>
</table>
</div>
</div>
</div>
Obviously I am missing something but I have tried adding to a DB and pulling it back out. I have tried ng-model and ng-bind for holding the variables. I am just lost on if or how I can get the td to be clickable and also switch where what is clicked displays. Thanks!
NOTE: disregard test1 in this example... I was using that earlier for testing getting the HTML out of the element.
The HTML doesn't need the <a> tag. Simply set the CSS style to cursor: pointer.
Also the ng-bind directive isn't necessary, simply bind model to HTML with double brace {{ }} expressions.
The DEMO
angular.module("app",[])
.controller('ChessCtrl' , function () {
var vm = this;
vm.test2 = "♔";
vm.test3 = "test";
vm.switch = function() {
var temp = vm.test2;
vm.test2 = vm.test3;
vm.test3 = temp;
}
});
.red { background-color: red; }
.grey { background-color: grey; }
td {
width: 20%;
cursor: pointer;
font-size: 24pt;
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ChessCtrl as vm">
<table>
<tr>
<td class="red" ng-click="vm.switch()">{{vm.test3}}</td>
<td class="grey" ng-click="vm.switch()">{{vm.test2}}</td>
</tr>
</table>
</body>
Okay, I try to figure out one solution that might work for you too.
I am adding code snippet have a look:
Main challange, that you are facing is, ng-bind,
have a look to this article and find the sole purpose of ng-bind
https://www.w3schools.com/angular/ng_ng-bind.asp
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<table style="width: 75%">
<tr>
<td id="td1" ><a ng-bind="link1" ng-click="clickMe()"></a></td>
<td id="td2" class="" ><a ng-bind="link2" ng-click="clickMeAgain()"></a>
</td>
<td>
</tr>
</table>
</div>
<script>
var clickMeIsClicked = false;
var clickMeAgainIsClicked = false;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.link1 = 'Click me to show td2';
$scope.link2 = ' I always want to be visible, thanks td1';
$scope.count = 0;
$scope.myFunction = function() {
$scope.count++;
}
$scope.clickMe = function(){
if(!clickMeIsClicked){
$scope.link2 = 'Click me to show td2';
$scope.link1 = ' I always want to be visible, thanks td1';
clickMeIsClicked = true;
}
else{
$scope.link1 = 'Click me to show td2';
$scope.link2 = ' I always want to be visible, thanks td1';
clickMeIsClicked = false;
}
}
$scope.clickMeAgain = function(){
}
});
</script>
</body>
</html>
I have to create a little program in AngularJS for my school, but I'm not very advanced yet, because I lack basic training.
I tried to make a texture move using arrow keys, but I didn't have any success finding a usable answer on the Internet.
I'd be happy if anyone would help me.
Here is the code I use for now to move it, if that helps:
<!DOCTYPE html>
<html>
<head>
<title>Angular Game</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body bgcolor="#151B54">
<div ng-app="myApp" ng-controller="myCtrl">
<div id="myDiv" ng-style=" {'position':'relative','height':'20px','width':'92px','background-color':'#348781','left': divleft+'px','top':divtop+'px'}">Raumschiff</div>
<input type="button" ng-mousedown="goLeft()" value="<"> <input type="button" ng-mousedown="goRight()" value=">"><br>
<input type="button" ng-mousedown="goDown()" value="v"> <input type="button" ng-mousedown="goUp()" value="^">
<input type="button" ng-click="startInterval()" value="start">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$interval) {
$scope.divleft = 200;
$scope.divtop = 300;
$scope.goRight = function ()
{
$scope.divvel2 +=1;
}
$scope.goLeft = function ()
{
$scope.divvel2 -=1;
}
$scope.goUp = function ()
{
$scope.divvel +=1;
}
$scope.goDown = function ()
{
$scope.divvel -=1;
}
$scope.moveDiv = true;
var intervalHandler;
$scope.divvel ="0";
$scope.divvel2 ="0";
$scope.startInterval = function ()
{
$interval.cancel(intervalHandler);
intervalHandler = $interval(myIntervalFunction,50);
}
myIntervalFunction = function()
{
$scope.divtop-=parseInt($scope.divvel);
$scope.divleft+=parseInt($scope.divvel2);
}
});
</script>
</body>
</html>
To make a texture move using arrow keys. Try this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$interval) {
$scope.divleft = 100;
$scope.divtop = 30;
$scope.goRight = function ()
{
$scope.divleft +=1;
}
$scope.goLeft = function ()
{
$scope.divleft -=1;
}
$scope.goUp = function ()
{
$scope.divtop -=1;
}
$scope.goDown = function ()
{
$scope.divtop +=1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div id="myDiv" ng-style=" {'position':'relative','height':'20px','width':'92px','background-color':'#348781','left': divleft+'px','top':divtop+'px'}">Raumschiff</div>
<input type="button" ng-mousedown="goLeft()" value="<"> <input type="button" ng-mousedown="goRight()" value=">"><br>
<input type="button" ng-mousedown="goDown()" value="v"> <input type="button" ng-mousedown="goUp()" value="^">
</div>
Angular has directives that will allow you to easily listen for key events.
I think ng-keyup should work fine for you.
You will need to add the ng-keyup directive to the body tag to make sure you listen for key events at the highest level. You will also have to move your ng-app and ng-controller directives to the body tag too so that the function that you declare for your key events is in the correct scope.
So change
<body bgcolor="#151B54">
<div ng-app="myApp" ng-controller="myCtrl">
to
<body bgcolor="#151B54" ng-app="myApp" ng-controller="myCtrl" ng-keyup="handleKeyup($event)">
<div>
You will then be able to do something with those events in your controller.
So add this to your controller:
$scope.handleKeyup = function (e) {
switch (e.which) {
case 37:
$scope.goLeft();
break;
case 38:
$scope.goUp();
break;
case 39:
$scope.goRight();
break;
case 40:
$scope.goDown();
break;
}
};
Iam new to AngularJS and was stuck at the concept of angular nested views with single controller. Gone through some examples here, which didn't help me. Below is the code from a question and I need 2 things here. After clicking on submit:
1.The date selected has to be assigned as input and url has to be constructed based on the date selected and the result from that url has to be displayed in Modal.
2.At the same time a table(present in tab-submit.html) has to displayed in the page(in tab.html) below the submit button from another URL.
Below is the code I have in app.js:
wc.controller('MyController', function ($scope, $modal, $log, $http, $location, $filter) {
var that = this;
var in10Days = new Date();
in10Days.setDate(in10Days.getDate() + 10);
$scope.dates = {
date3: " "
};
this.dates = {
date3: new Date()
};
this.open = {
date3: false
};
// Disable weekend selection
this.disabled = function (date, mode) {
return (mode === 'day' && (new Date().toDateString() == date.toDateString()));
};
this.dateOptions = {
showWeeks: false,
startingDay: 1
};
this.timeOptions = {
readonlyInput: false,
showMeridian: false
};
this.dateModeOptions = {
minMode: 'year',
maxMode: 'year'
};
this.openCalendar = function (e, date) {
that.open[date] = true;
};
$scope.format = 'yyyy-MM-dd%20HH:mm';
debugger;
$scope.open = function () {
var date = $filter("date")($scope.dates.date3, $scope.format);
$http.get(http://myurlPartA+date+"myurlPartB")
.success(function (response) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return response;
}
}
});
});
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
Here is a plunker:http://plnkr.co/edit/xKbkFGoa3p5y5NAzueut?p=preview. Is it possible to get solution for my question??Hope anyone will help me to understand this.
Thanks in advance!!
Requirements
1. Have a page with two tabs
2. If click the tab1, should load the page with date picker and a submit button
3. After selecting a date picker I will click the submit button
4. Then from a url I should get the data for particular date which I have selected.
5. There will be two api calls, one for modal and one for table
6. Then modal should show up with the data
7. After closing the modal, table should below the submit button
As I understood from your discussion, I think this is what you wanted to do.
Have a page with two tabs
If click the tab1, should load the page with date picker and a submit button
After selecting a date picker I will click the submit button
Then from a url I should get the data for particular date which I have selected.
There will be two api calls, one for modal and one for table
Then modal should show up with the data
After closing the modal, table should below the submit button
I saw few issues in your codes.
Some issues in Directive, the way you use
Getting data from api
How you open and close the modal
How you print data in table
I have a updated, working Plunker here.
Please find the below code changes. In the codes you are getting the codes for Modal. but I dont know how you will bind it. Please change it as you want.
index.html
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: darkgrey;
}
</style>
<link rel="stylesheet" type="text/css" href="jquery.datetimepicker.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.datetimepicker.full.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="ui-bootstrap-tpls.js"></script>
<script src="datetime-picker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="application.js"></script>
</head>
<body ng-app="wc">
<ul>
<li><a ui-sref="tab">Tab1</a></li>
<li><a ui-sref="tabs">Tab2</a></li>
</ul>
<div class="container">
<div ui-view></div>
</div>
</body>
</html>
application.js
var wc = angular.module('wc', ['ui.router','ui.bootstrap', 'ui.bootstrap.datetimepicker']);
wc.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/posts');
$stateProvider
.state('tab', {
url: '/tab1',
templateUrl: 'tab.html'
})
.state('tabs', {
url: '/tabs',
templateUrl: 'tabs.html',
});
});
wc.controller('SampleController', function ($scope, $http, $modal) {
$scope.subt_click = function () {
//Selected Date is here use as you want
//$scope.mydate
alert($scope.mydate);
//Modal Data
$http.get("http://jsonplaceholder.typicode.com/posts")
.success( function(response) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalController',
resolve: {
items: function () {
return response;
}
}
});
});
//Table Data
$http.get("http://jsonplaceholder.typicode.com/posts")
.success( function(response) {
$scope.tableData = response;
});
};
});
wc.controller('ModalController', function ($scope, $modalInstance, items) {
$scope.modalData = items;
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
wc.directive('datetimepicker', function () {
return {
require: 'ngModel',
link: function (scope, el, attr, ngModel) {
$(el).datetimepicker({
onSelect: function (dateText) {
scope.$apply(function () {
ngModel.$setViewValue(dateText);
});
}
});
}
};
});
Tab.html
<div class="jumbotron text-top" ng-controller="SampleController">
<h4>Select from below:</h4>
<form class="form-horizontal">
<input datetimepicker="" ng-model="mydate" type="text" readonly-input="true" />
<a class="btn btn-info" ng-click="subt_click()">Submit</a>
</form>
<div class="table-responsive" ng-show="tableData.length > 0">
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in tableData">
<td>{{x.id}}</td>
<td>{{x.body}}</td>
</tr>
</tbody>
</table>
</div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>Info</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="x in modalData">
{{ x.id + '-' + x.title}}
</li>
</ul>
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Close</button>
</div>
</script>
$stateProvider is best used for navigating to an entirely different page in your app . For modals , dom animations ect .. This should be put in a directive .
Example
wc.directive('modal', function(){
return {
restrict: "A",
template: 'modal.html' // FYI the html for the actual modal popup
link: function(scope,elem,attrs){
$(".modal").show();
}
}
})
for instance ; in your modal.html would contain something like this
<div class="modal" style="display:none;">
</div>
then in your main document
<div modal></div>
//Or you can place this on whatever element you desire to show the modal
I want to allow the user to enter only positive numbers in the textbox
My code is as follows:
script.js file contents:
angular.module("myfapp", []).controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
angular.module('myApp', []).controller('MainCtrl', function($scope) {
app.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
var clean = val.replace(/[^0-9]+/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
});
angular.html contents as follows:
<html>
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>
<style>
.entry {
width: 300px;
margin: 10px auto;
text-align: center;
}
</style>
</head>
<body ng-app="myfapp">
<div ng-controller="HelloController" >
<h2 class="entry">Welcome {{ helloTo.title }} to the world of Tutorialspoint!</h2>
</div>
<section ng-app="myApp" ng-controller="MainCtrl">
<h4 class="entry">AngularJS Numeric Value Widget</h4>
<div class="well entry">
<label>Employee Age
<input type="text" ng-model="employee.age" placeholder="Enter an age" valid-number/>
</label>
</div>
</section>
</body>
</html>
Why does it not work?
Can anyone run it and check please!
Change your input type to number, then you can use min directive to specify the minimum number allowed.
<input type="number" ng-model="employee.age" placeholder="Enter an age" min="0"/>
There are a lot of problems with your code.
you've nested ng-app which is not allowed normally, use a single ng-app with multiple ng-controller.
your need to use restrict inside your directive to restrict its usage to one or multiple types (i.e. A=Attribute,E=Element,C=Class), like in this case restrict: "A"
When specifying a controller its generally a good practice to use array with the last element being the controller function and the first ones being all the services factories you are using in string format
#MajidYaghouti's suggestion is good to use ng-change but if you insist on using directives I have done some bit of corrections to your code.
Use some code formatting dude, and name your stuff cautiously and elegantly.
your script.js
angular.module("myfapp", []).controller("HelloController", ["$scope", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
}])
.controller('MainCtrl', ["$scope", function($scope) {
}])
.directive('validNumber', function() {
return {
restrict: "A",
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (val === null)
return;
var myRegex = /\d+\.(\d{1,2})?/;
var clean = myRegex.exec(val)[0];
if (val != clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
and your index.html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<script src="script.js"></script>
<style>
.entry {
width: 300px;
margin: 10px auto;
text-align: center;
}
</style>
</head>
<body ng-app="myfapp">
<div ng-controller="HelloController" >
<h2 class="entry">Welcome {{ helloTo.title }} to the world of Tutorialspoint!</h2>
</div>
<section ng-controller="MainCtrl">
<h4 class="entry">AngularJS Numeric Value Widget</h4>
<div class="well entry">
<label>Employee Age
<input type="text" ng-model="employee.age" placeholder="Enter an age" valid-number/>
</label>
<div>
{{ employee.age }}
</div>
</div>
</section>
</body>
</html>
updated plunkr
Please view my JSFiddle
I have a fairly wonkey interaction that on a div mouseenter/mouseleave toggles a input checkbox on/off. If said checkbox is set true, it then sets a focus of an adjacent input text field.
I would like to isolate this interaction into a directive that will allow me to duplicate without conflict.
i've color coated the boxes for reference
<body ng-app="ngApp" ng-controller="MainCtrl">
<div class="row">
<div class="span2 box red" leave-edit="uncheckInputBox(false)" enter-edit="checkInputBox(true)">hover</div>
<span class='span8'>
<p>red</p>
<input type="checkbox" ng-model="isChecked">
<input xng-focus='isChecked' ng-model="editingInput">
{{isChecked}}
{{editingInput}}
</span>
</div>
<div class="row">
<div class="span2 box blue" leave-edit="uncheckInputBox(false)" enter-edit="checkInputBox(true)">hover</div>
<span class='span8'>
<p>blue</p>
<input type="checkbox" ng-model="isChecked">
<input xng-focus='isChecked' ng-model="editingInput">
{{isChecked}}
{{editingInput}}
</span>
</div>
</div>
js
var app = angular.module('ngApp', [])
app.controller('MainCtrl', ['$scope', function ($scope) {
'use strict';
$scope.isChecked = false;
$scope.$watch('isChecked', function(newV){
newV && $('#name').focus();
},true);
$scope.checkInputBox = function(val) {
$scope.isChecked = val;
};
$scope.uncheckInputBox = function(val) {
$scope.isChecked = val;
};
}]);
app.directive('xngFocus', function() {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.xngFocus,
function (newValue) {
newValue && element.focus();
},true);
}
};
});
app.directive('leaveEdit', function(){
return function(scope, element, attrs) {
element.bind('mouseleave', function() {
scope.$apply(attrs.leaveEdit);
});
};
});
app.directive('enterEdit', function(){
return function(scope, element, attrs) {
element.bind('mouseenter', function() {
scope.$apply(attrs.enterEdit);
});
};
});
css
.box {
height:50px;
cursor:pointer;
color: #fff;
text-align: center;
}
.red {
background: red;
}
.blue {
background: blue;
}
Strange interaction, but okay. You need to not use the same scope for each directive since you want them to be isolated.
I just did this by creating a scope for a directive that has the shared template.
app.directive('why', function() {
return {
scope: {},
link: function($scope, elt, attrs) {
//setup in here
}, ...
A few other things:
Don't include angular through external resources and in the framework section of fiddle. It runs angular over your dom twice and will behave strangely.
Also there are ng-mouseenter and ng-mouseleave directives in angular so you don't need to implement those.
The updated fiddle is here
Hope this helped!