Question

I am using ng-repeat and setting a model with it similar to the following

<div ng-repeat="thing in things" ng-model="thing"  my-directive>
    {{thing.name}}
</div>

then in my directive it looks something like this

.directive("myDirective, function () {
    return {
        require: 'ngModel',
        link: function(scope, lElement, attrs, model) {

         console.log(model.name);// this gives me 'NAN'
        }
    }
})

My question is how can I access the values in the model? I tried model.$modelValue.name but that did not work.

Was it helpful?

Solution

If you want to bind in a scoped value then you can use the '=' in an isolated. This will appear on the scope of your directive. To read the ng-model directive, you can use =ngModel:

.directive("myDirective", function () {
    return {
        scope: {
            model: '=ngModel'
        }
        link: function(scope) {

         console.log(scope.model.name); // will log "thing"
        }
    }
});

OTHER TIPS

.directive("myDirective", function () {
    return {
        require: 'ngModel',
        link: function(scope, lElement, attrs, model) {

         console.log(attrs.ngModel); // will log "thing"
        }
    }
})

If your directive does not have isolated or child scope then you can do this:

.directive('someDirective', function() {
    return {
        require: ['^ngModel'],
        link: function(scope, element, attrs, ctrls) {
            var ngModelCtrl = ctrls[0];
            var someVal;
            // you have to implement $render method before you can get $viewValue
            ngModelCtrl.$render = function() {
                someVal = ngModelCtrl.$viewValue;
            };
            // and to change ngModel use $setViewValue
                    // if doing it in event handler then scope needs to be applied
            element.on('click', function() {
                var val = 'something';
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(val);
                });
            });
        }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top