从$ scope获取数据

时间:2014-02-11 17:59:50

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

首先,我想说我刚刚开始使用AngularJS,所以如果这是一个愚蠢的问题,请原谅。

我有一个执行AJAX请求的控制器,它返回一个JSON对象。然后将此JSON保存为$scope.person。它看起来像这样:

function PersonController($scope, $http) {
  $http({
    method: 'GET',
    url: constants.adminUrl + '/getJSON.php?data=person'
  }).success(function(data, status, headers, config) {
    $scope.person = data;
  }).error(function(data, status, headers, config) {
    throw new Error('I\'m truly sorry, but I couldn\'t fetch your data');
  });
}

文件getJSON.php成功返回我期望的内容,JSON对象如下所示:

[{
  "id": 1,
  "firstName": "Silvestre",
  "lastName": "Herrera",
  "headline": "Diseñador y front-end engineer",
  "location": "Argentina",
  "summary": "Summary summary summary"
}]

然后,在我的HTML中,我有以下内容:

<ol ng-controller="PersonController">
  <li ng-repeat="person in person | filter: {id:1}">
      <input data-autoGrow name="firstName" type="text" value="{{ person.firstName }}" placeholder="<?= __("What's your first name?"); ?>"><input data-autoGrow name="lastName" type="text" value="{{ person.lastName }}" placeholder="<?= __("And your last name?"); ?>">
  </li>
  <li ng-repeat="person in person | filter: {id:1}"><input type="text" value="{{ person.headline }}" placeholder="<?= __("Headline"); ?>"></li>
  <li ng-repeat="person in person | filter: {id:1}"><input type="text" value="{{ person.location }}" placeholder="<?= __("Where do you live?"); ?>"></li>
  <li ng-repeat="person in person | filter: {id:1}"><textarea placeholder="<?= __("Write something about you..."); ?>">{{ person.summary }}</textarea></li>
</ol>

所有PHP函数__()都会翻译给定的字符串。无论如何,你可以看到我使用ng-repeat指令,我想避免,因为只有一个人,而且总会只有一个人。

我尝试使用ng-model="person"元素中的<ul>代替ng-repeat="person in person"中的<li>,然后尝试打印{{ person.firstName }},但不会打印任何内容。但是,如果我打印{{ person }},我确实得到了整个对象。

嗯,我想这几乎总结了我的问题。提前感谢任何输入!

3 个答案:

答案 0 :(得分:2)

你不能这样做吗?:

$scope.person = data[0];

答案 1 :(得分:2)

在设置HTML标记的内容时,不要使用ng-model指令。 ng-model是处理表单字段中value属性的Angular方式。出于您的目的,您应该能够写下:

<ol ng-controller="PersonController">
  <li>
    <input data-autogrow name='firstName' ng-model='person[0].firstName'/>
    <input data-autogrow name='lastName' ng-model='person[0].lastName'/>
  </li>
  <li><input ng-model='person[0].headline'/></li>
  <li><input ng-model='person[0].location'/></li>
  <li><textarea ng-model='person[0].summary'/></li>
</ol>

注意,textarea标记实际上不是vanilla HTML,它是AngularJS directive实现相同的功能,所以它不能以完全相同的方式工作,你仍然可以绑定{{1 }}而不是像在vanilla HTML中那样将其插入到内容中。

答案 2 :(得分:0)

您不能对数组中的数组和项使用相同的变量名'person'。你的代码应该是

$scope.people = data;

然后在html中

<li ng-repeat="person in people | filter: {id:1}">
相关问题