【问题标题】:AngularJS $viewValue is undefinedAngularJS $viewValue 未定义
【发布时间】:2018-07-30 01:35:16
【问题描述】:

我对 Angular 很陌生,并尝试实现这个 Angular 按钮复选框绑定:JSFIDDLE,但是我收到错误 “无法读取未定义的属性 '$viewValue'” 当我在浏览器控制台上调试时,ctrl 显示为未定义。我在 StackOverflow 上尝试了很多答案,但经过数小时的尝试后仍然卡住。

HTML

<div class="btn-group" data-toggle="buttons-checkbox">
    <button type="button" ng-model="myModel.optionA"
            ng-show="myModel.optionA" class="btn">A</button>
    <button type="button" ng-model="myModel.optionB"
            ng-show="myModel.optionB" class="btn">B</button>
</div>

JS

app.controller("productCatalogController", ["$scope", "$http", "$compile", "$timeout", 
function($scope, $http, $compile, $timeout) { ... }



app.directive('button', function() {
return {
    restrict: 'E',
    scope: {
        'ngModel': '='
    },
    link: function(scope, element, attr, ctrl) {
        if (!element.parent('[data-toggle="buttons-checkbox"].btn-group').length) {
            return;
        }

        scope.$watch('ngModel', function(newValue, oldValue) {
            element.toggleClass('active', ctrl.$viewValue);

        });

        element.bind('click', function(e) {
            scope.$apply(function(scope) {
                ctrl.$setViewValue(!ctrl.$viewValue);
            });
            e.stopPropagation();
        });
     }
    }

 });

【问题讨论】:

  • 您发布的小提琴是功能性;小提琴和你的代码有什么不同?
  • @Claies 按照 Daniel 下面的建议,我将 ngModel 与 require 绑定,看起来这是唯一的区别。它摆脱了最初的错误,但它显示了新的错误:“控制器'ngModel',指令'按钮'所需,找不到!”。我使用了这个语法:require: 'ngModel'
  • 为指令选择一个名称而不是button 会更明智。否则,该指令会将自身附加到模板中的每个按钮,包括您不想像复选框一样操作的按钮。这很可能是问题所在。不是复选框的按钮现在需要 ng-model 指令。
  • @georgeawg 是的,这绝对是问题所在,所有按钮都在尝试获取 ng-model 指令。我重命名了指令,现在它运行良好。谢谢!

标签: angularjs angularjs-directive angularjs-ng-model


【解决方案1】:

不要简单地用scope 绑定到ngModel。像这样使用require:

'require': 'ngModel'

【讨论】:

  • 我这样做了,它消除了错误,但是即使两个复选框都未选中,按钮也会显示:/
  • @nfiona 你是什么意思?你的小提琴似乎工作,按钮显示/隐藏基于复选框值
  • @Daniel 那是别人的小提琴,我试图在我的项目中实现它。对不起,应该澄清一下。从上面的 georgeawg 中找到了解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 2013-05-28
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多