Angular JS - NG Model

by mrajcok

HTML

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<ng-form name="myform">
    <test-ng-model ng-model="someObj.model" name="myel"></test-ng-model>
    <pre>{{someObj.model | json}}</pre>
</ng-form>

JavaScript

var app = angular.module('my-app', [], function () {

})

app.controller('AppController', function ($scope, $log) {
    $scope.someObj = { model: ''};
    $scope.$watch('someObj.model', function (value) {
        $log.log('object watch', JSON.stringify(value))
    })
    $scope.$watch('someobj.model', function (value) {
        $log.log('property watch', JSON.stringify(value))
    }, true)
})

app.directive(
    'testNgModel', [
    '$timeout',
    '$log',

function ($timeout, $log) {

    function link($scope, $element, attrs, ctrl) {
        var counter1 = 0, counter2 = 0;
        
        ctrl.$render = function () {
            $element.find('.result').text(JSON.stringify(ctrl.$viewValue))
        }

        $element.find('.one').click(function () {
            if ($scope.$$phase) return;
            $scope.$apply(function () {
                var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
                form.counter1 = ++counter1;
                ctrl.$setViewValue(form);
            });
        });
        $element.find('.two').click(function () {
            if ($scope.$$phase) return;
            $scope.$apply(function () {
                var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
                form.counter2 = ++counter2;
                ctrl.$setViewValue(form);
            });
        });

        $scope.$watch(attrs.ngModel, function (current, old) {
            ctrl.$render()
        }, true)
    }

    return {
        require: 'ngModel',
        restrict: 'E',
        link: link,
        //if isolated scope is not set it is working fine
        scope: true,
        template: '<div><input type="button" class="one" value="One"/><input type="button" class="two" value="Two"/><span class="result"></span></div>',
        replace: true
    };

}]);