1

I need to know how I can use a class in angularjs.

A simple class like this:

function Person(name,age){
    this.name=name;
    this.age=age;
    this.getAge(){
       return age;
    };
    //etcetera
}

I am learning angular but I can't find an answer to this. I want to create Person instances and use the name, age etc. in the view.

Please a simple solution because I am from a C# OOP background and don't know js frameworks. But I want to use the MVC pattern. Thanks!

1
  • I recommend using jsFiddle or plunker to post what you have understood and what code you have tried. Others can comment on it and help you if you post your fiddle or plunker. Commented Nov 27, 2014 at 14:57

2 Answers 2

1

AngularJS is a framework that is written in and used through JavaScript. Although JavaScript has many object oriented features, it handles inheritance quite differently. This used to be confusing to me too until I read the excellent: JavaScript: The Good Parts by Douglas Crockford. I suggest you read this, it's quite a brief book and points out differences in approach in a very clear and concise manner.

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

Comments

1

Your syntax is almost right, you just need to change the function declaration a bit:

function Person(name, age) {
    this.name = name;
    this.age = age;

    this.getAge = function () {

        return age;
    };
}

Then you can create an instance like this:

var p = new Person("John", 26);

And do a call like this:

console.log(p.name + ' is ' + p.getAge() + ' years old');

Here it is in JS Fiddle.

In general, I highly recommend using Typescript, it complements angularjs in an excellent way. It makes your project very scalable, and adds intellisense. You can declare interfaces, classes, etc.

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.