将键值对附加到angularjs对象

时间:2016-09-22 03:57:34

标签: angularjs

我从laravel 5.2表单请求验证获得json输出

我的json输出是:

{
    "title": [
        "The title field is required."
    ],
    "description": [
        "The description field is required."
    ],
    "address.city": [
        "City field is required"
    ]
}

将此输出附加到对象

var self = this;
self.error = {
    address: {}
};

var onFailure = function (response) {
    angular.forEach(response.data, function(value, key) {
        self.error[key] = value[0];
    });
};

我想访问此错误对象到我的视图,对于“address.city”,我无法使用“ctrl.error.address.city”访问它,其余我可以访问

如何使用包含“。”的键追加对象。并在视图中显示它?

3 个答案:

答案 0 :(得分:1)

这是你需要的。但最好不要在属性名称中包含(。)。相反,您可以使用下划线(_)。避免使用点(。)作为属性名称中的字符。

var myApp = angular.module('MyApp', []);

myApp.controller('MyCtrl', function ($scope) {
 $scope.foo={};
    $scope.foo['hello.There'] = "I'm foo!";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
    {{foo["hello.There"]}}<br />
    <input type="text" ng-model="foo['hello.There']" />
</div>

答案 1 :(得分:0)

如果您知道密钥名称,那么您可以访问它的唯一方法是[]

查看小提琴以获取更多信息。

https://jsfiddle.net/9f4mbh1h/1/

答案 2 :(得分:0)

您需要将代码更改为此

控制器中的

myApp.controller('MyCtrl', function ($scope) {
 $scope.foo={};
$scope.foo "hi";
  });

in html

<div ng-app="MyApp" ng-controller="MyCtrl">
  <input type="text" ng-model="foo" /> </div>
相关问题