1

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:

http://jsfiddle.net/1Lwg20wz/

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 ?

1
  • You are right. Avoid using $rootScope, so your code can be self contained. About your answer, I'm watching for it. Commented Nov 8, 2015 at 22:24

1 Answer 1

2

First a couple of small issues in your example:

  1. 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.

  2. 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/

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

1 Comment

Thanks a lot. I've tried to use articleService in view. I thought that I can access to articleService without to define in controller.

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.