Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two instance of the same controller in angular js

I run into this problem (I know it's not a good practice). I have a single view that has a split screen. On the left side you have an input field and on the right side you see the input field value. Both of the sides has the same controller, but I use the state provider with ui-view attribute.

index.html

<div class="col-sm-6" ui-view="left-side">
<div class="col-sm-6" ui-view="right-side">

app.js

$stateProvider.state('/',{
        url: '/',
         views:{
            'left-side':  {
                templateUrl: 'leftside.html',
                controller: 'testController'
            },
            'right-side': {
                 templateUrl: 'rightside.html'
                 controller: 'testController'
            }
        }

rightside.html

<div class="container">
    <p>{{item}}</p>
</div>

leftside.html

<div class="container">
    <input ng-model="item" />
</div>

and in the testController.js

app.controller('testController, function($scope){
    $scope.item = 'some text value';
});

I know that each of the ui-view has a seperate (instance of?) scope. Is there a way to make the changes on the right side if i write something in the input field on the left side?

like image 620
cs.matyi Avatar asked Apr 01 '26 09:04

cs.matyi


1 Answers

You can declare controller option outside views, so that will initialize only once

Code

$stateProvider.state('/',{
    url: '/',
    controller: 'testController',
    views:{
       'left-side':  {
       templateUrl: 'leftside.html'
    },
      'right-side': {
       templateUrl: 'rightside.html
    }
}
like image 150
sumair Avatar answered Apr 03 '26 21:04

sumair