Last active
August 29, 2015 14:06
-
-
Save NickTomlin/4a6ef6ed9223511c598f to your computer and use it in GitHub Desktop.
Angular directive controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html ng-app="Demo"> | |
<head> | |
<meta charset="utf-8" /> | |
<title> | |
Directive controllers and wrapper error states | |
</title> | |
<style> | |
.input-group-error { | |
border: 1px solid red; | |
} | |
</style> | |
</head> | |
<body ng-controller="MyController as ctrl"> | |
<h1> | |
Directive controllers and wrapper error states | |
</h1> | |
Model1: {{ctrl.child1}} | Model2: {{ctrl.child2}} | |
<p>Unaffected model: {{ctrl.unaffected}}</p> | |
<hr> | |
<form name="myForm"> | |
<input type="text" ng-model="ctrl.unaffected"> | |
<div parent class="one"> | |
Parent 0 | |
<input type="text" name="child1" ng-maxlength=3 ng-model="ctrl.child1" child> | |
</div> | |
<hr> | |
<div parent class="one"> | |
Parent 1 | |
<input type="text" name="child2" ng-maxlength=3 ng-model="ctrl.child2" child> | |
</div> | |
</form> | |
<!-- Load scripts. --> | |
<script src="angular.js"></script> | |
<script src="app.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var id = 0; | |
var app = angular.module( "Demo", [] ); | |
app.controller('MyController', [function () { | |
this.foo = 'foo'; | |
}]); | |
app.directive( | |
"parent", | |
[function() { | |
function Controller($scope, $element) { | |
this.register = function (elem) { | |
this.elem = elem; | |
}; | |
this.setInvalid = function (invalid) { | |
if (invalid) { | |
$element[0].classList.add('input-group-error'); | |
} else { | |
$element[0].classList.remove('input-group-error'); | |
} | |
}; | |
} | |
return({ | |
controller: Controller, | |
}); | |
}]) | |
.directive("child", [function () { | |
return { | |
require: ['^parent', '^form'], | |
link: function (scope, elem, attrs, controllers) { | |
var parent = controllers[0]; | |
var ctrl = controllers[1]; | |
var $input = ctrl[attrs.name]; | |
parent.register(elem); | |
elem.on('blur', function () { | |
parent.setInvalid($input.$invalid && $input.$dirty); | |
}); | |
} | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment