如何从自定义指令中访问$ modelValue和$ viewValue?

时间:2016-06-14 09:29:49

标签: angularjs angularjs-directive

尝试从自定义指令中访问$modelValue$viewValue时,我收到null

var demo = angular.module('demo', []);
demo.directive('dogInfo', function($parse) {
    return {
        restrict: 'E',
        require: 'ngModel',
        template: "<div> Dog's name: {{dogname}}<br>View Name: {{viewValue}}<br>Model Value: {{modelValue}}<br> Tag name: {{tagName}}</div>",
        link: function (scope, element, attrs, controller) {
            scope.viewValue = controller.$viewValue;
            scope.modelValue = controller.$modelValue;
            scope.tagName = controller.$name;
        }
    }});

function MyCtrl ($scope) {
    $scope.dogname = 'Hero';  // now    
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<div ng-app='demo'>
    <p ng-controller='MyCtrl'>
       <dog-info ng-model="dogname" name="Doggggyyy"/>.
    </p>
</div>

我收到了这个输出:

Dog's name: Hero
View Name: null
Model Value: null
Tag name: Doggggyyy

这是小提琴:http://jsfiddle.net/cxdun3y8/3/

2 个答案:

答案 0 :(得分:1)

尝试这种方法:

demo.directive('dogInfo', function($parse) {
    return {
        restrict: 'E',
        require: 'ngModel',
        template: "<div> Dog's name: {{dogname}}<br>View Name: {{model.$viewValue}}<br>Model Value: {{modelValue}}<br> Tag name: {{tagName}}</div>",
        link: function (scope, element, attrs, controller) {
            scope.model = controller;
            scope.viewValue = controller.$viewValue;
            scope.modelValue = controller.$modelValue;
            scope.tagName = controller.$name;
        }
    }});

注意我如何将数据传递给视图

答案 1 :(得分:0)

根据答案here,有三种可行的解决方案

1)使用$timeout等到第一次摘要结束

$timeout(function() {
  initialViewValue = controller.$viewValue;
}, 0)

2)使用scope.watch

const off = scope.$watch(attrs.ngModel, () => {
  initialViewValue = controller.$viewValue;
  off();
});

3)使用$parse立即获取价值

const getter = $parse(attrs.ngModel);
let initialViewValue = getter(scope);

viewValue也可用作格式化程序回调中的参数

controller.$formatters.push(function(value) {
   viewValue = value
});

如果您只想获取初始值

,则可能需要删除回调