0

スコープ内にオブジェクトの配列があり、それをディレクティブで更新したいとします。どうやってやるの ?何をすべきかよくわかりません。

要点は、この場合は ID である名前と「衛星データ」でスコープを更新したいということですが、それ以上のものがあると想像できます。

質問: わざわざ UI に表示しないのに、なぜ id 値が必要なのですか? 代わりに、データベースと対話していて、データベースが入力値 + 対応する ID に基づいて値を返していると想像してください。この ID は、たとえばフォームを送信するときに使用されます。

もう 1 つ: ディレクティブから people 変数に直接アクセスしたくありません。ディレクティブが一般的ではないためです。ここにプランクを作成しました: http://plnkr.co/edit/D2ybe8uPSdzeIxTFzad5

HTML ファイル :

<body ng-controller="MainCtrl">
<span ng-repeat="val in people">
     <input customattr type = "text" ng-model="val.name" />   
    <br /> <br/>  Children :
  <span ng-repeat="v in val.children">
 <input customattr type = "text" ng-model="v.name" />   
  </span>
</span>    
</body>

JS ファイル:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.people = [{"name":"Toto", "id":1,
    "children": [
      {"name":"John","id":2},
      {"name":"Mary","id":3}      
      ]
    }];

});

app.directive('customattr', function () {
  return {
      restrict: 'A',
      link: function (scope, element, attrs) {
          element[0].onblur = function() {
           console.log("Hello there" + element[0].value);
           // make some magic processing of the input with a XHR request here...
           // for the demonstration the XHR request is replaced by findTheNewDict
           var newDict = findTheNewDict(element[0].value);
           console.log(newDict);
           // Now we want to update the scope with the data
           // How can we do that ?
           scope.$apply(function(s) {
            // We have no knowledge of the variable people here
            // We just know that the data is a dict containing a name and an id
           });
          }              
          findTheNewDict = function(input) {
            // Just a dummy return : it doesn't matter what is returned
            // The main point is that I want to update the right variable
            // in the scope with this data
            return {"name": input + "a", "id":input.length};
          }
      } 

  }; 
});
4

2 に答える 2

0

あなたは指令で必要以上のことをしようとしているようです。「newDict」とは何ですか? ID 値を変更する理由 なぜ名前の長さに??!

次の行を plunk に追加しました。これにより、入力時に「人」オブジェクトが変更されていることがわかります。

<p>{{people}}</p>

あなたの「customattr」ディレクティブはまったく何もしていないので、私はそれを使用しませんでした. おそらく、各「家族」の「子を追加」ボタンと「親を追加」ボタンが必要ですか?それらは、コントローラーへの直接関数呼び出しを使用して html に含めることができます。それらも追加しました。

参照: http://plnkr.co/edit/ABaCc8lu5fBJJjpii5LP?p=preview

于 2013-04-23T01:57:29.723 に答える