当我需要 ngModel 控制器时,如何访问模型控制器的属性



我正在使用ng-repeat并使用它设置类似于以下内容的模型

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

那么在我的指令中它看起来像这样

.directive("myDirective, function () {
    return {
        require: 'ngModel',
        link: function(scope, lElement, attrs, model) {
         console.log(model.name);// this gives me 'NAN'
        }
    }
})

我的问题是如何访问模型中的值?我尝试了model.$modelValue.name但没有奏效。

如果要

绑定作用域值,则可以在隔离值中使用"="。 这将出现在您的指令范围内。 要阅读 ng-model 指令,您可以使用=ngModel

.directive("myDirective", function () {
    return {
        scope: {
            model: '=ngModel'
        }
        link: function(scope) {
         console.log(scope.model.name); // will log "thing"
        }
    }
});
.directive("myDirective", function () {
    return {
        require: 'ngModel',
        link: function(scope, lElement, attrs, model) {
         console.log(attrs.ngModel); // will log "thing"
        }
    }
})

如果您的指令没有独立或子作用域,则可以执行以下操作:

.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);
                });
            });
        }
    }
});

最新更新