如何在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>
答案 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"
。
请参考以下问题..