javascript - Angular changes JSON string -


i'm trying show data on screen using angularjs, asp.net , json.net. when i'm calling $.getjson returns normal jsonarray, when i'm putting data in this.variablename inside angular controller, data changes , angular won't display in view.

model

public class directory {     public int id { get; set; }     public string name { get; set; }     public list<note> notes { get; set; }     public int parentid { get; set; }     public list<int> directoryids { get; set; }      public virtual directory parent { get; set; }     public virtual icollection<directory> directories { get; set; } } 

.net controller action

public string getdirectories() {     var directories = db.directories.where(d => d.parentid.equals(0)).tolist();      return jsonconvert.serializeobject(new { directorylist = directories }, formatting.indented,                     new jsonserializersettings                     {                         referenceloophandling = referenceloophandling.ignore                     }); } 

angular js

(function () {     var app = angular.module('notes', []);      app.controller('directorycontroller', function () {         this.directories = directories; //check output 1     });      var directories = $.getjson("/directory/getdirectories", function (data) {         return data; //check output 2     }); })(); 

output 1 (larger image http://i62.tinypic.com/2ppd0kg.png) the output angular makes of json

output 2

this want use gets changed in output 1

as claies commented , protector 1 answered, getjson call asynchronous , way couldn't fill var directories before page loads.

the answer use $http.get within controller , use variable store context of controller, have done var cont = this. needed initialize directories variable empty array avoid errors on page load.

then later on assign data within success promise directories variable.

(function () {     var app = angular.module('notes', []);      app.controller('directorycontroller', ['$http', function ($http) {         var cont = this; //save context         cont.directories = []; //empty array avoid errors on page load          $http.get('/directory/getdirectories').           success(function (data, status, headers, config) {               //save async data directories in right context               cont.directories = data;           }).           error(function (data, status, headers, config) {           });     }]); })(); 

thanks help. both comment @claies , answer @protector 1 helped me find fit answer myself.

if has better answer, feel free post it, can mark answer.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -