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

时间:2013-12-21 19:13:19

标签: angularjs angularjs-directive angularjs-ng-repeat angularjs-controller

我正在使用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,但这没效果。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

如果要绑定范围值,则可以使用&#39; =&#39;在一个孤立的。这将出现在您的指令范围内。要阅读ng-model指令,您可以使用=ngModel

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

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

答案 2 :(得分:0)

如果你的指令没有隔离或子范围,那么你可以这样做:

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