AngularJS: Directive watch controller scope

by Sajeetharan Sinnathurai

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.min.js"></script>
<div ng-controller="MyCtrl">
    <form ng-submit="onSubmitted()">
        <input type="name" ng-model="sample" value="Ready to roll for second time!"/>
        <input type="submit" value="submit to scope value"/>
    </form>

    <hr/>
    
    Some other form here. Think line items
    
    <hr />
    <span some-directive>Text in template</span>

    

</div>

JavaScript

var app = angular.module('myApp', []);

function MyCtrl($scope) {

    $scope.flashMessage = "Ready to roll!";
    $scope.sample="Ready to roll for second time!";
    
    $scope.onSubmitted = function() {
        $scope.flashMessage = $scope.sample;
    };
}


app.directive("someDirective", function() {
    return {
        link: function(scope, element, attrs) {
            
            scope.$watch("flashMessage", function() {
                element.text(scope.flashMessage);
            });

            
        }
    }
});