Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay
    This lesson is outdated. Click here to find out about changes you should be aware of.

    Defining a Method on the Scope

    John LindquistJohn Lindquist

    Armed with Controllers and service factories, you'll probably want to do some work on the data to give your app behaviors. In this video we will look at providing that behavior by defining a method on the scope. This method will be bound within the HTML and update live as input changes.

    angularjsAngularJS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    John Lindquist: Defining a method on your controller or on the scope in your controller is actually pretty straightforward. We'll just define a method called "reversed message," and this will be the function that returns scope data message. I'll split it up and reverse it, and then join it back together.

    Then all we'll do in here is instead of saying, "data message," we'll invoke our method and say, "reversed message." We should be set up, so this is reversed. Now you can see it says, "This is reversed." That's really all you need to do, is just to find a method on your scope, give it a function that does something.

    What I want to show you here that I see a lot of people do, is as much as possible, you don't want to reference the scope inside of a function, because we can really extract this out and pass in the message into our reversed message. We'll say, "We will pass in the data message," and then this can be just be "message," because we can pass in our message here.

    That removes the dependency of the scope inside of our function, and makes it easier to test and all that sort of stuff.

    You can see it works just the same as it always did. But now instead of having this scope dependency inside of your method here, you're just passing in the value into your method. So, much cleaner, a much better way of approaching that. Again, just message, message, and it returns our value.

    It's just going to update that and do that check any time it sees the scope change, so that should be often enough for things like binding. If one of the scope models changes, it will revoke this reverse message function as well. So, there you go.

    Discuss

    Discuss