4

I have the following codes :

The state (lets just make it short for simplicity purposes)

.state('foo', {
    url: '/foo',
    templateUrl: 'path/to/template.html',
    controller:'fooCtrl',
})

The controller

controller = function($scope){
    // not the actual code
    $scope.barCount
}

template.html

<div>
    <span>{{ barCount }}</span> // this is updating properly
</div>

Other html partial

<div ng-controller="fooCtrl">
    <span>{{ barCount }}</span> // this is **NOT** updating properly
</div>

I have a scope variable on my controller. The 2-way binding is working fine on the template that was declared on the state together with the controller. But not on the other partial template where in I binded the controller using the ng-controller.

Is this some kind of bug? Or am I missing something? Thanks.

10
  • 3
    I am really new to AngularJS but shouldn't you use {{ }} in the div? Commented Jan 16, 2016 at 10:30
  • do you wanted to preserve last value of count, and you want it on other state to be same? Commented Jan 16, 2016 at 10:31
  • @shrestha_aj oh thanks for pointing that out. Typo mistake. :) Commented Jan 16, 2016 at 10:37
  • @PankajParkar I dont really get what you're trying to say but what I wanted is that both template should update accordingly based on the value from the controller Commented Jan 16, 2016 at 10:39
  • 4
    @TheGreenFoxx no. your guess is wrong..if you are sharing same controller amongst different partials. they both will have new instance of controller.the scope variable change in 1st partial wouldn't replicate in other controller.as they are different instance. you have to create a service to share data in your application Commented Jan 16, 2016 at 10:46

1 Answer 1

3

You have one Controller but two instances of that controller. Each time you use ng-controller or declare it in differents views a new instance is created, so all controllers are in differents scopes. The best way to share data between controller are services, because these are singleton, so they have one instance. Example:

angular.module('app')

.factory('fooService', [function(){
  var bar = 'Shared Data';
  return {
    getBar: function(){
      return bar;
    }
  };
}])

.controller('FooController', ['fooService', function(fooService){
  this.barCount = fooService.getBar();
  // or use $scope.barCount = fooService.getBar();
}];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.