Angularjs同步不同部分的值但在同一模块下同一个控制器

时间:2014-04-22 04:59:19

标签: angularjs scope

如何在2个控制器中同步$ scope.department。无论我输入哪个输入值,$ scope.department仍然可以根据输入字段进行更新。 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>

2 个答案:

答案 0 :(得分:0)

您可以像这样在Angular JS中创建一个常量。

因此Department将始终包含“人力资源部门”。

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

});

但你应该做类似下面的事情来实现你所提到的场景

<强> 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>

<强>脚本

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;
    }
});

答案 1 :(得分:0)

如果您想在controllers之间共享变量,请使用$rootScope

指定$rootScope.department = "somehting"

请参考以下问题..

Sharing scope between controller & directive in AngularJS