AngularJS $ viewValue是未定义的

时间:2018-07-30 01:35:17

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

我对Angular还是很陌生,并尝试实现此Angular Buttons-复选框绑定: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();
        });
     }
    }

 });

1 个答案:

答案 0 :(得分:1)

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

'require': 'ngModel'