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;
};
});
答案 0 :(得分:1)
您有menu
个控制器的2个独立实例,它们不共享相同的范围
更新其中一个范围时,另一个不了解范围。您可以使用服务跨控制器共享数据或更改使用实现单独控制器实例的结构
答案 1 :(得分:1)
如果你定义两次ng-controller,两者都会有分开的范围。
您需要将控制器的所有用法放在一个块中:
<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>