1

I have a small controller and some basic data. Here is my code. I am not sure why when I click the link, my messages won't show. In the console, I get no errors at all. I consoled the variables, and they show up. For some reason, it doesn't work in the view. I am not sure what I am missing.

index.html -- navigation menu

<ul class="nav navbar-nav" ng-controller="menu">
        <li class="active"><a href ng-click="showMessage('Home')">Home</a></li>
        <li><a href ng-click="showMessage('Work')">Work</a></li>
        <li><a href ng-click="showMessage('Contact')">Contact</a></li>
      </ul>

<div class="container" ng-controller="menu">
 <h1> {{ message }} </h1>
</div><!-- /.container -->

Controller

angular.module('website', [])
.controller('menu', function($scope) {
    // show the message on click
    $scope.showMessage = function(messages) {
        $scope.message = messages;
        console.log($scope.message);
        return $scope.message;
    };
});

2 Answers 2

1

If you define two times the ng-controller, both will have separated scope.

You need to put all usages of controller in a block:

<div ng-controller="menu">
    <ul class="nav navbar-nav">
        <li class="active"><a href ng-click="showMessage('Home')">Home</a></li>
        <li><a href ng-click="showMessage('Work')">Work</a></li>
        <li><a href ng-click="showMessage('Contact')">Contact</a></li>
    </ul>

    <div class="container">
        <h1> {{ message }} </h1>
    </div>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I made the changes, and that was the issue.
1

You have 2 separate instances of the menu controller and they do not share the same scope

When you update one of the scopes, the other has no knowledge of it. You can use a service to share data across controllers or change structure you are using implementing separate controller instances

1 Comment

Thank you! I see what you mean.

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.