首页 > 解决方案 > 使用 ng-change 将值从 ng-model 传递到另一个 ng-model 时出错

问题描述

对于“a.html”的第一个输入,用户可以从下拉列表中选择或输入一个值。

对于第二个输入,默认值设置为与第一个输入相同。用户稍后可以更改第二个输入中的值。然后来自第二个输入的值将传递给 b.js 的函数 setPath。

在第一个输入中输入值“android”后,第二个输入也将默认为“android”。删除第二个输入中的所有值并尝试输入新值后,出现控制台错误。它说“无法在字符串'android'上创建属性名称。

一个.html

 // first input
<input type="text" ng-model="result.c" data-auto-select="true"
       ng-change="result.path = result.c; checkIfMatch()"
       ng-blur="checkIfMatch()" bs-options="c as c.name for c in cs" />

 // second input
<input type="text" ng-disabled="!result.c.id" ng-model="result.path.name"/>

一个.js

  $scope.checkIfMatch = function(){
      if(!$scope.result.c || $scope.result.c && $scope.result.c.id){
         return;
      } else{  
         var c = $scope.result.c;
          for(var i = 0; i < $scope.cs.length; i++){
            if(c == $scope.cs[i].name){
              $scope.result.c = $scope.cs[i];
              return;
            }
          }
      }
  };

b.js

function setPath() {
   $modal.open({
       templateUrl: '/xxx/a.html',
       scope: scope,
       controller: 'aController',
       windowClass: 'aModal'
      }).result.then(function(result){
     // scope.result.path.name to be the same value as second input in a.html
         var anchorTag = '<a href="' + result.c.id +'">Launch '+  result.path.name + '</a>';
 }

如果我在 a.html 中更改第一个输入的 ng-change 代码,则将光标移出第一个输入后,第二个输入的值不会显示。twitter bootstrap bs-options 仍然是新手。

<input type="text" ng-model="result.c" data-auto-select="true"
       ng-change="result.path = result.c.name; checkIfMatch()"
       ng-blur="checkIfMatch()" bs-options="c as c.name for c in cs" />

// 第二个输入

<input type="text" ng-disabled="!result.c.id" ng-model="result.path"/>

标签: angularjstwitter-bootstrapangularjs-scopeangularjs-ng-modelangularjs-ng-change

解决方案


推荐阅读