2015-10-15 78 views
8

給予裏面的代碼我的控制器:使用表達式Angular.js

$scope.entity = { 
    firstName: 'Jack', 
    lastName: 'Bauer', 
    location: { 
    city: 'New York' 
    } 
}; 
$scope.path = 'location.city'; 

如何動態綁定ngModelpath指定的entity的財產?

我已經試過這樣的事情,但無濟於事:

<input ng-model="'entity.' + path"> 

回答

7

Slava,我不太確定這是否是一個好主意。但無論如何, 您需要通過將此屬性添加到輸入ng-model-options="{ getterSetter: true }來使您的模型getterSetter知道。 然後你需要一個控制器中的一個函數來構建一個getterSetter。

<input type="text" ng-model="propertify('entity.' + path)" ng-model-options="{ getterSetter: true }"> 

這就是結果模板的外觀。

幸運的是,angular有一個$ parse的服務,這使得這更容易。所以像這樣的東西需要在你的控制器中,或者在注入服務中更好。

$scope.propertify = function (string) { 
     var p = $parse(string); 
     var s = p.assign; 
     return function(newVal) { 
      if (newVal) { 
       s($scope,newVal); 
      } 
      return p($scope); 
     } ; 
    }; 

這將返回一個getter-setter函數來處理這個問題。 看到它在行動this plunk

+0

桑德,你是一個真正的角度忍者,非常感謝你! =) –

+0

我仍然得到這個「不可轉讓」的錯誤...但你的plunkr工作正常 – ProblemsOfSumit

+0

我有錯誤的角度版本 - 一切都很好,謝謝! – ProblemsOfSumit

2

你可以使用括號標記少許修改,因爲你要綁定一個嵌套屬性。你必須在路徑分割的財產:

<input ng-model="entity[locationKey][cityKey]"/> 

控制器:

$scope.locationKey = 'location'; 
$scope.cityKey = 'city'; 

js fiddle

+0

謝謝你,但它不會做,我存儲在一個單一變量的完整路徑,這是問題的核心。 –

7

更新

它並不如預期的工作,該值正確顯示,但無法更改。正確的解決方案由Sander here提供。


不正確的解決方案

哇,解決它意外:

<input type="text" ng-model="$eval('entity.' + path)"> 

而這裏的Plunk

我希望它能幫助別人。

1

在閱讀和使用桑德埃利亞斯的答案後,我用這個,但遇到了另一個問題。

當與ng-required="true"結合他的結果<input>你不能空場,因爲當領域將是空的,newVal作爲undefined通過。

經過一些更多的研究,我發現an isssue on GitHub地址和解決這個問題。

這裏是Sander的和GitHub的答案組合的樣子:

$scope.propertify = function (string) { 
    var property = $parse(string); 
    var propAssign = property.assign; 
    return function (newVal) { 
     if (arguments.length) { 
      newVal = angular.isDefined(newVal)? newVal : ''; 
      propAssign($scope, newVal); 
     } 
     return property($scope); 
    }; 
}; 

argument.length反映了被傳遞到的getter/setter值的數量,將是0在get和1一組。

此外,我添加了angular.isDefined()作爲Sumit suggested in a comment也保存false和空("")值。

這裏是一個updated Plunker