2013-04-22 83 views
0

假設您在作用域中有一個對象數組,並且您想用指令更新它。我怎樣才能做到這一點 ?我不確定應該怎麼做。使用衛星數據更新範圍

重點是我想更新範圍名稱和「衛星數據」,這是在這種情況下的id,但我們可以想象,我們有更多的。

問題:爲什麼我需要一個id值,如果我不打算在UI中顯示它呢?想象一下,相反,我們正在與一個數據庫交談,並且數據庫正在根據輸入值+相應的ID返回一個值。這個id將在提交表單時被使用。

還有一件事:我們不想直接訪問指令中的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}; 
      } 
     } 

    }; 
}); 

回答

0

$範圍是什麼是綁定到視圖。假設你的視圖元素(div等)綁定到$ scope對象中的屬性,只需更新其他任何JavaScript對象的屬性,框架將負責其餘的部分。

您可能需要將更新邏輯封裝在$ scope。$ apply函數中,具體取決於您在哪裏運行它。

+0

是的。假設我們不想直接修改指令中的people變量,你會怎麼做?在屬性中附加一個函數? – JohnCastle 2013-04-23 07:26:14

+0

是的。將數據作爲參數發送。 – Ketan 2013-04-23 15:17:12

0

您似乎試圖做的事情超過您的指令所需要的。什麼是'newDict'?爲什麼改變id值?爲什麼要長的名字??!

我添加下面一行到你的普拉克,它可以讓你看到你的「人」的對象被修改爲您鍵入:

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

你「customattr」指令是做什麼都沒有,所以我沒不會使用它。您可能需要按鈕在每個「家庭」中添加「添加孩子」,並添加到「添加父母」?他們可以通過直接函數調用到控制器中;我也加了這些。

參見:http://plnkr.co/edit/ABaCc8lu5fBJJjpii5LP?p=preview

+0

非常感謝,但你根本不回答我的問題,爲什麼你覺得我需要添加孩子並添加父按鈕?這完全不是我的問題。也許我還不夠清楚:我增加了更多解釋。 「爲什麼名稱的長度」=這只是一個虛擬的回報,並不重要什麼是回報,這只是如果你想要的問題的簡化版本。 – JohnCastle 2013-04-23 07:23:32

+0

我沒有回答你的問題。即使有更多的解釋,這個說法也不是很清楚。 「衛星數據」是什麼意思?祝你好運。 – 2013-04-23 18:34:39

+0

衛星數據是隨身攜帶的數據,應該保留,但不考慮我們所看到的算法/操作。在這種情況下,數據是名稱,衛星數據是ID。這是我在CLRS中的算法簡介中讀到的一個概念。 – JohnCastle 2013-04-23 19:16:23