2

How to synchronize $scope.department in 2 controllers. no matter I enter the value in which input, the $scope.department still can update base on the input field. example

Angularjs  
var app = angular.module('app', []);

    app.controller('GreetCtrl', function($scope) {
    $scope.department= "HR department";

  });

HTML
<body ng-app="app">
  <div class="show-scope-demo">
    <div ng-controller="GreetCtrl">
      <input type="text" ng-model="department">
      {{department}}
    </div>

    <div ng-controller="GreetCtrl">
     <input type="text" ng-model="department">
     {{department}}
    </div>
  </div>
</body>
4
  • Do you want $scope.department to be constant? Commented Apr 22, 2014 at 5:12
  • @Henry just Take a look at my Answer Commented Apr 22, 2014 at 5:34
  • @Madhu: no, I want it be dynamic Commented Apr 22, 2014 at 6:14
  • @NidhishKrishnan: I think you miss understood my question, but anyway thank for giving me a respond. Actually what I want is the $scope.department can be update in both controller at the same time. Commented Apr 22, 2014 at 6:18

2 Answers 2

0

You can create a constant in Angular JS like this.

So Department will always contains "HR department".

var app = angular.module('app', []);
app.constant("Department", "HR department");
app.controller('GreetCtrl', function ($scope, Department) {
    $scope.department = Department;

});

But you should do something like the below to acheive the scenerio which you have metioned

Working Demo

html

<div class="show-scope-demo">
    <div ng-controller="GreetCtrl">
        <input type="text" ng-model="department" ng-change="preventChange()">{{department}}</div>
    <div ng-controller="GreetCtrl">
        <input type="text" ng-model="department" ng-change="preventChange()">{{department}}</div>
</div>

script

var app = angular.module('app', []);
app.constant("Department", "HR department");
app.controller('GreetCtrl', function ($scope, Department) {
    $scope.department = Department;
    $scope.preventChange = function () {
        $scope.department = Department;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to share the variable between the controllers then use $rootScope.

assign $rootScope.department = "somehting".

Please refer the below question..

Sharing scope between controller & directive in AngularJS

1 Comment

I had tried, but it cannot work. example

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.