Skip to content

Instantly share code, notes, and snippets.

@msandrini
Created January 30, 2015 17:15
Show Gist options
  • Save msandrini/056dd2ca5e8084e670df to your computer and use it in GitHub Desktop.
Save msandrini/056dd2ca5e8084e670df to your computer and use it in GitHub Desktop.
Angular two-way controllers
<div ng-app="demo">
<div ng-controller="demoCtrl">
<h2>Two-way controllers (change any)</h2>
<input type="text" ng-model="inp"
maxlength="2" ng-blur="refactor()">
<select ng-model="sel">
<option value="{{x}}"
ng-repeat="(x,obj) in options">
{{obj.label}}
</option>
</select>
</div>
</div>
var a = angular.module('demo',[]);
a.controller('demoCtrl',function($scope){
$scope.options = [
{n:1, label:'01 - one'},
{n:2, label:'02 - two'},
{n:3, label:'03 - three'},
{n:4, label:'04 - four'},
{n:5, label:'05 - five'},
{n:10, label:'10 - ten'},
{n:20, label:'20 - twenty'},
];
$scope.$watch('sel',function(v){
var val = $scope.options[v].n;
$scope.inp = val;
});
$scope.$watch('inp',function(v){
var contador = 0;
$scope.options.forEach(function(obj){
if (obj.n === parseInt(v)){
$scope.sel = contador;
}
contador++;
});
});
$scope.refactor = function(){
if ($scope.inp<10){
$scope.inp = '0' + $scope.inp;
}
}
});
input{
font-size:18px;
width:80px;
padding:7px;
}
select{
font-size:17px;
padding:8px 8px 7px;
}
div{
padding:5px 10px;
}
h2{
font-family:sans-serif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment