Question

I am very confuse about using ngModelController. For example a controller from directive you can require like this.

myModule.directive('amValidateName', ['validate', function (validate) {
    return {
        restrict: 'A',
        scope: {
            errorName: '='
        },
        require: 'ngModel',

        link: function (scope, elm, attrs, ngModelCtrl) {
        }
    }
}]);

But it is allow too to use ngModelCtrl on the ng-controller like this

myModule.controller('SignUpCtrl', ['$scope', 'validate', function ($scope, validate) {

        //Can i use ngModelController here, methods like $setPristine()?

}]);

i found this sentence in the angular documentation

Such DOM related logic should be provided by other directives which make use of NgModelController for data-binding.

It means, i shuold use ngModelController only by require to other directive, like the first example.

Was it helpful?

Solution

You can interact with each model controller via the form controller that is published on $scope. During ngModel's linking phase it registers with its parent form directive, in turn the form's controller is published to $scope. This gives you a single point on $scope to interact with your form and any models on the form. Here is a simple example where your controller check's to see if the form is dirty when the user tries to go to a new route:

app.controller('myController', ['$scope', '$window', function ($scope, $window) {
    $scope.$on('$locationChangeStart', function (event) {
        if ($scope.myForm.$dirty) {
            if (!$window.confirm('You have unsaved changes. Do you want to discard all changes?')) {
                event.preventDefault();
            }
        }
    });
}]);

Now it's debatable if you should be doing these types of logic inside your controller or in a separate directive. The above example is simple, but when you want to do things like set validation state on errors received by your server after you've used your controller to post to your server, then I see absolutely no reason why this should not be applied inside your controller.

Updated: As per @charlietfl comment below, form must have name and that name becomes the scope variable form object is bound to, e.g:

<form name="myForm">
</form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top