AngularJS 1.0.1 Click Example
Shows how AngularJS 1.0.1 requires two passes for a directive with two way binding to update a scope variable.
by justbn
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<body ng-app="app" ng-controller='AppCtrl'>
<p>{{ sharedText }} </p>
<p>{{ goodText.text }} </p>
<shared-text-directive text="sharedText"></shared-text-directive>
</body>
JavaScript
var app = angular.module('app', []);
app.controller('AppCtrl', [ '$scope', function($scope) {
$scope.sharedText = 'This will not change.';
}]);
app.directive('sharedTextDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
text: '='
},
template : '<button>Click Me For New Text</button>',
link: function( scope, element, attrs ) {
element.click( function() {
var random = Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
console.log('Before Changing Text: ' + scope.text);
scope.text = 'Random Number: ' + random;
console.log('After Changing Text: ' + scope.text);
scope.$apply('text');
console.log('Before Applying : ' + scope.text);
});
}
};
});