0

I am working on an angular app trying to call an child object method within a repeater. I have a selected item which has a company item. The company class has a getAddressText() method, which returns the address text for the company, which iw ould like to show on screen.

Below is the code to help my explanation. In the application I see that ctrl.selectedItem.Company is correctly loaded, but it appears to be ignoring the call to the function.

HTML + AngularJS code:

<span>{{ctrl.selectedItem.Company.getAddressText()}}</span>

Typescript:

namespace app.controllers {
    class MyController {
        public selectedItem: app.models.Item;
    }
}
namespace app.models {
    export class Item {
        public Company: Company;
        constructor() {}
    }
    export class Company {
        constructor() {}
        getAddressText(): string {
            return "Some text...";
        }
    }
}
4
  • where do you create instance of Item? Commented Jun 29, 2016 at 14:11
  • ctrl.selectedItem is binded to a repeater that displays a list of items. When the user clicks on an item, the code is ng-click="ctrl.selectedItem=item" . This is how ctrl.selectedItem value is set. Commented Jun 29, 2016 at 16:00
  • and the list you get from service or something (json)? Commented Jun 29, 2016 at 16:07
  • Yes, I get the list using a service. The service returns the list in json format. Commented Jun 29, 2016 at 17:26

1 Answer 1

1

The problem is that you're getting plain js objects from service (json). They may look like Item and Company (have the same properties), but they don't have the expected methods.
If you want to have instances of mentioned types you should map json objects to these types (for example in your service or using $http transform response if you're getting data through $http service):

var convertedItems = jsonItems.map(i => {
    var item = new Item();
    item.Company = new Company();
    //map required properties from i (or use some library for cloning)
    return item;
});

Another approach would be to move logic(methods) to helper class or maybe to controller or service and leave data objects clean (in this case interface definition will be enough).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.