Hey, asked a question on StackOverflow here 
<http://stackoverflow.com/q/26496385/1216976> and figured this would also 
be a good place to ask.

I have a simple validator that checks an input against a regex:

    .directive('test', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, element, attrs, ctrl) {

            ctrl.$setValidity('namePattern', true);

            function checkValid(name) {
                console.log('checkValid executed');
                if (!name || ctrl.$pristine) {
                    ctrl.$setValidity('namePattern', true);
                    return name;
                }
                var test = /^[A-Za-z0-9_-]+$/;
                ctrl.$setValidity('namePattern', test.test(name));
                return name;
            }

            // called when value changes via code/controller
            ctrl.$formatters.unshift(checkValid);
            // called when value changes in input element
            ctrl.$parsers.unshift(checkValid);
        }
      };
    });

Live example: http://jsfiddle.net/1uv79jnL/1/

I want to unit test this directive, and have the following:

    function initState() {
      angular.mock.module('app');
      angular.mock.inject(function($compile, $rootScope, $timeout){
        $scope = $rootScope.$new();

        $rootScope.safeApply = function(cb) {
          $timeout(function() {
            $scope.$digest();
          });
        };

        $scope.model = {
          instanceName: ''
        };

        var tmpl = angular.element('<form name="form">' +
          '<input ng-model="model.instanceName" name="instanceName" 
validate-name-pattern>' +
          '</form>'
        );

        element = $compile(tmpl)($scope);
        $scope.$apply();
        form = $scope.form;
      });
    }
    beforeEach(initState);


However, changes to the model don't trigger `checkValid`.  I've tried 
directly setting a property on the model:

    it('should trigger a change resulting in an invalid state', function () 
{
      $scope.model.instanceName = 'this is an invalid name';
      $scope.$digest();
      expect(form.instanceName.$valid).to.be.false;
    });

as well as monkeying around with `$modelValue`:

    it('should trigger a change resulting in an invalid state', function () 
{
      form.instanceName.$modelValue = 'this is an invalid name';
      $scope.$digest();
      expect(form.instanceName.$valid).to.be.false;
    });


How can I trigger a model change so that `checkValid` runs via 
`$formatters`?

(This is using Angular 1.2.23)

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to