使用卫星数据更新范围

问题描述:

假设您在作用域中有一个对象数组,并且您想用指令更新它。我怎样才能做到这一点 ?我不确定应该怎么做。使用卫星数据更新范围

重点是我想更新范围名称和“卫星数据”,这是在这种情况下的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}; 
      } 
     } 

    }; 
}); 

$范围是什么是绑定到视图。假设你的视图元素(div等)绑定到$ scope对象中的属性,只需更新其他任何JavaScript对象的属性,框架将负责其余的部分。

您可能需要将更新逻辑封装在$ scope。$ apply函数中,具体取决于您在哪里运行它。

+0

是的。假设我们不想直接修改指令中的people变量,你会怎么做?在属性中附加一个函数? – JohnCastle 2013-04-23 07:26:14

+0

是的。将数据作为参数发送。 – Ketan 2013-04-23 15:17:12

您似乎试图做的事情超过您的指令所需要的。什么是'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