0

I'm having some trouble understanding how to use ng-controller. I've a form controller in eventController.js.

<html ng-app>
<head>
<script src="angular.js"></script>
<script src="eventController.js"></script>
</head>
<body> 
<div>
<h3>My Event:<i>{{event.name}}</i></h3>
</div>
<div ng-controller="formController">
<form >
<label>Event Name:</label>
<input type="text" ng-model="event.name" placeholder="Event Name">
</form>
</div>
</body>
</html>

Now the heading even.name is not getting displayed when I'm using ng-controller="formController" in that division otherwise its working fine. When I use ng-controller on the whole page as a division then I get {{event.name}} and not the content.

How can I display the content of event.name and also use the controller on form together ?

What mistake am I making ?

1 Answer 1

3

The event.name property is only set within the scope of the controller being used. In your case, the <div> tag introduces a new scope. Within it, {{event.name}} will be data-bound to and replaced by the value of event.name.

In your code example, the <h3> tag lives outside of the scope defined by <div ng-controller="formController">, so {{event.name}} won't be data-bound against your model property.

To solve your problem, put the ng-controller attribute on a common ancestor element of your heading and the form, like that:

<div ng-controller="formController">
    <div>
        <h3>My Event:<i>{{event.name}}</i></h3>
    </div>
    <form >
        <label>Event Name:</label>
        <input type="text" ng-model="event.name" placeholder="Event Name" />
    </form>
</div>

For a slightly more complex example, check out the documentation: AngularJS: ngController.

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

2 Comments

I tried that earlier, but I'm getting {{event.name}} and not the binded data <body> <div ng-controller="formController"> <div> <h3>My Event:<i>{{event.name}}</i></h3> </div> <form > <label>Event Name:</label> <input type="text" ng-model="event.name" placeholder="Event Name">
@Anathema.Imbued Take a look at this JSFiddle showing that the solution is indeed working: jsfiddle.net/tAnNp.

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.