user3125407
user3125407

Reputation: 101

Append key value pair to angularjs object

I am getting json output from laravel 5.2 form request validation

My json output is:

{
    "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

How to append object with key containing "." and show it in view?

Upvotes: 1

Views: 1247

Answers (3)

zeeshan Qurban
zeeshan Qurban

Reputation: 387

You need to change your code to this

in your controller

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>

Upvotes: 0

Manish
Manish

Reputation: 5066

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.

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>

Upvotes: 1

Deendayal Garg
Deendayal Garg

Reputation: 5148

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/

Upvotes: 0

Related Questions