Skip to content

Instantly share code, notes, and snippets.

@amitittyerah
Last active August 29, 2015 14:03
Show Gist options
  • Save amitittyerah/c2edd121a6b28c0c7c8e to your computer and use it in GitHub Desktop.
Save amitittyerah/c2edd121a6b28c0c7c8e to your computer and use it in GitHub Desktop.
Two-way binding and watching the bound value
<!DOCTYPE>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script>
// Create a parent app
var app = angular.module('app', []);
// A single controller to rule them all
app.controller('ParentController', ['$scope', function ($scope){
$scope.property1 = 0;
$scope.property2 = 1;
$scope.togglevar1 = false;
$scope.togglevar2 = false;
$scope.pushTime = function(index) {
$scope['property' + index] = new Date().getTime();
}
}]);
// The box directive
// We create 2 different instances with their own controllers
app.directive('box', ['InstancedService', function (InstancedService){
return {
restrict: 'E',
replace: true,
scope: {
index: '=',
binding: '='
},
template: '<button ng-click="show()">Click Me! {{binding}}</button>',
controller: function ($scope){
console.log($scope.propertybinding);
$scope.service = new InstancedService.Obj($scope.index),
$scope.show = function () {
console.log($scope.service.index);
};
$scope.$watch(function() { return $scope.binding; }, function (val){
console.log($scope.binding);
});
}
};
}]);
// Another isolated directive to control the box directive
app.directive('bigButton', function (InstancedService){
return {
restrict: 'E',
replace: true,
scope: {
togglevar: '='
},
template: '<button ng-click="toggle()">Big Button o toggle! {{togglevar}}</button>',
controller: function ($scope){
$scope.toggle = function () {
$scope.togglevar = !$scope.togglevar;
};
}
};
});
// Non-singleton service
app.factory('InstancedService', function(){
function Obj(index){
this.index = index;
}
return {
Obj: Obj
}
});
</script>
</head>
<body>
<div ng-app='app'>
<div ng-controller='ParentController as parentCtrl'>
<button ng-click="pushTime(1);">Show Time 1</button>
<button ng-click="pushTime(2);">Show Time 2</button>
<br/>
<box index="1" binding="property1" ng-show="togglevar1"></box>
<box index="2" binding="property2" ng-show="togglevar2"></box>
<br/>
<big-button togglevar="togglevar1"></big-button>
<big-button togglevar="togglevar2"></big-button>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment