【问题标题】:How to access $modelValue and $viewValue from inside custom directives?如何从自定义指令中访问 $modelValue 和 $viewValue?
【发布时间】:2018-03-29 18:50:36
【问题描述】:

在尝试从自定义指令内部访问 $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/

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案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;
        }
    }});

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

【讨论】:

  • 我不明白..您只是为控制器创建了一个别名,并直接访问了模板中的 viewValue 属性。为什么我的方法不起作用?
  • 因为在第一种情况下,您获得了指向直接值的链接,该值是空的(目前)并且只会在那时更改。在第二种情况下,您会得到对象,并且每个摘要都会重新评估值。并且永远是真实的
  • ok.. 我可以在链接函数本身中获取 viewValue 吗?我需要它在范围内设置它,以便我可以在模板中访问它..
  • 什么意思?只是 $scope.value
  • 我明白了。您可以通过多种方式实现这一目标。最自然的,是总是询问 ngModelController。像这样:函数 callTheDog() {return ngModelCtrl.$viewValue + '被调用';但是您也可以将您的侦听器推送到 ngModelCtrl.$viewChangeListeners 并且当值发生更改时,您将收到通知,因此您可以对您的值进行处理。
【解决方案2】:

根据答案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
});

如果您只想获取初始值,您可能希望删除回调

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    相关资源
    最近更新 更多