简体   繁体   English

将键值对附加到 angularjs 对象

[英]Append key value pair to angularjs object

I am getting json output from laravel 5.2 form request validation我正在从 laravel 5.2 表单请求验证中获取 json 输出

My json output is:我的 json 输出是:

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

Appending this output to object将此输出附加到对象

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

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

I want to access this error object to my view, for "address.city", I can't access it using "ctrl.error.address.city", rest I can access我想在我的视图中访问这个错误对象,对于“address.city”,我无法使用“ctrl.error.address.city”访问它,其余的我可以访问

How to append object with key containing "."如何使用包含“.”的键附加对象and show it in view?并在视图中显示它?

Here is what you need.这是你需要的。 But its better not to have (.) in a property name.但最好不要在属性名称中包含 (.)。 Instead you can use a underscore(_).相反,您可以使用下划线 (_)。 Avoid using dot(.) as a chaaracter in property names.避免在属性名称中使用 dot(.) 作为字符。

 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>

if you know the key name then the only way you can access it is by [] .如果您知道密钥名称,那么您可以访问它的唯一方法是通过[]

Check the fiddle for more info.检查小提琴以获取更多信息。

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

You need to change your code to this您需要将代码更改为此

in your controller在你的控制器中

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

in html在 html 中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM