2016-09-22 67 views
1

我正在从laravel 5.2形式请求验证JSON输出追加键值对angularjs对象

我的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”,其余我可以访问

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

回答

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>

0

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

检查小提琴的更多信息。

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

您需要更改您的代码此

在控制器

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

在HTML

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