Reputation: 789
I beginning on this framework.
And I've a question about update a controller from another controller.
I know this question has many times asked.
But it's not like my problem.
I can resolve my problem with rootScope, but I don't like (Am I wrong ?)
This is my example:
I thought it would update automatically with this part of code:
this.article = articleService.article;
I would like to update my PanelController when I click on "Read news".
How do you do ?
What is the best practice ?
Upvotes: 1
Views: 52
Reputation: 38490
First a couple of small issues in your example:
In the following HTML:
<a href="#" ng-click="selectArticle(article.index)" class="btn btn-default">
View news
</a>
Change href="#"
to href=""
. Otherwise it will navigate to the root of your application instead of executing the ng-click
.
In the same HTML change ng-click="selectArticle(article.index)"
to ng-click="main.selectArticle(article.index)"
.
Now to the main issue.
In the PanelController
you have the following code:
this.article = articleService.article;
This will copy the reference stored in articleService.article
to this.article
.
If articleService.article
held a reference to the article object with id 1, this.article
now also holds a reference to that object. They are however, two different references.
You have the following code to set the selected article object:
this.selectArticle = function(setArticle) {
articleService.article = articleService.articles[setArticle - 1];
};
Now articleService.article
will hold a reference to another article object, for example with id 2. But, this.article
in PanelController
will still hold a reference to the article object with id 1.
The easiest solution to achieve what you want is to use the original articleService.article
reference in your view, instead of creating a copy of it.
In PanelController
this.articleService = articleService;
In HTML:
<h1>{{panel.articleService.article.title}}</h1>
<p>{{panel.articleService.article.content}}</p>
Demo: http://jsfiddle.net/7ccop2hy/
Upvotes: 2