-
-
Save tlareg/bc710004e469a571826b to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/yacuqaduro
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> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div ng-app="demo"> | |
<div ng-controller="demoController as dCtrl"> | |
<input type="text" ng-model="dCtrl.number"> | |
<div>Number: {{ dCtrl.number }}</div> | |
<div dd-square ng-model="dCtrl.number"></div> | |
</div> | |
</div> | |
<script id="jsbin-javascript"> | |
angular.module('demo', []); | |
function DemoController() { | |
this.number = 5; | |
} | |
angular.module('demo').controller('demoController', DemoController); | |
function SquareController() { | |
this.square = 0; | |
} | |
angular.module('demo').directive('ddSquare', function() { | |
return { | |
restrict: 'A', | |
require: ['ddSquare','ngModel'], | |
template: [ | |
'<div>', | |
'<div>Square: <input ng-model="squareCtrl.square"></div>', | |
'<div>Square: {{squareCtrl.square}}</div>', | |
'<div>', | |
].join(''), | |
controllerAs: 'squareCtrl', | |
controller: SquareController, | |
link: function(scope, el, attrs, ctrls) { | |
var ctrl = ctrls[0]; | |
var ngModel = ctrls[1]; | |
ngModel.$render = function() { | |
var val = ngModel.$modelValue; | |
ctrl.square = val * val; | |
}; | |
scope.$watch(function () { | |
return ctrl.square; | |
}, function(newVal) { | |
var sqrtVal = Math.sqrt(parseInt(newVal, 10)); | |
if (sqrtVal && sqrtVal%1 === 0) { | |
ngModel.$setViewValue(sqrtVal); | |
} else { | |
ngModel.$setViewValue(''); | |
} | |
}); | |
} | |
}; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment