错误:[ngModel:nonassign]表达式不可分配

时间:2014-06-12 06:22:40

标签: angularjs ng-grid

尝试根据同一行中的另一个值显示gridcollection中的columnvalue。 用户可以选择/更改包含带有值的网格的模态中的值。当模态关闭时,值将被传回。那时我想为'又称'设置一个值:

HTML:

 Also known as: <input type="text" `ng-model="displayValue(displayNameData[0].show,displayNameData[0].value)">`

我在范围上创建了一个函数,仅在'show'值为true时选择值:

$scope.displayValue = function (show, val) {
    if (show) {
        return val;
    }
    else {
        return '';
    }
}

然而,当我关闭模态时,我收到一个错误:

Error: [ngModel:nonassign] Expression 'displayValue(displayNameData[0].show,displayNameData[0].value)' is non-assignable. 

plnkr参考:http://plnkr.co/edit/UoQHYwAxwdvX0qx7JFVW?p=preview

3 个答案:

答案 0 :(得分:38)

使用ng-value而不是ng-model为我工作。

答案 1 :(得分:16)

正如HackedByChinese所提到的,你不能将ng-model绑定到一个函数,所以试试这样:

<input type="text" ng-if="displayNameData[0].show"
                   ng-model="displayNameData[0].value">

或者,如果您希望此控件可见,您可以创建指令,将函数添加到$parsers,根据show设置空值:

    angular.module('yourModule').directive('bindIf', function() {
        return {
            restrict: 'A',
            require: 'ngModel',

            link: function(scope, element, attrs, ngModel) {
                function parser(value) {
                    var show = scope.$eval(attrs.bindIf);
                    return show ? value: '';
                }

                ngModel.$parsers.push(parser);
            }
        };
    });

HTML:

<input type="text" bind-if="displayNameData[0].show"
                   ng-model="displayNameData[0].value">

答案 2 :(得分:7)

You can bind ng-model to function

  

绑定到getter / setter
  有时将ngModel绑定到a是有帮助的   getter / setter函数。 getter / setter是一个返回a的函数   使用零参数和集调用时模型的表示   使用参数调用时模型的内部状态。它的   有时用于具有内部的模型   表示与模型公开的表示不同   图。

的index.html

<div ng-controller="ExampleController">
  <form name="userForm">
    <label>Name:
      <input type="text" name="userName"
             ng-model="user.name"
             ng-model-options="{ getterSetter: true }" />
    </label>
  </form>
  <pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>

app.js

angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
  var _name = 'Brian';
  $scope.user = {
    name: function(newName) {
     // Note that newName can be undefined for two reasons:
     // 1. Because it is called as a getter and thus called with no arguments
     // 2. Because the property should actually be set to undefined. This happens e.g. if the
     //    input is invalid
     return arguments.length ? (_name = newName) : _name;
    }
  };
}]);