以下是我正在尝试的代码:
var app = angular.module('app', []);
var appCtrl = app.controller('AppCtrl', AppCtrl);
function AppCtrl(){
var appCtrl = this;
appCtrl.variable = "search";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app">
<div ng-controller = "AppCtrl as ctrl1">
{{ctrl1.variable}}
</div>
<div ng-controller = "AppCtrl as ctrl2">
<input type="search" ng-model = "ctrl2.variable"/>
{{ctrl2.variable}}
</div>
</div>
当我更新ctrl2.variable
时,ctrl1.variable
未更新。
如何在不使用$scope
的情况下更新?
答案 0 :(得分:1)
我可以在不使用 $scope.$watch
的情况下找到的最简单的解决方案是使用共享状态,如下所示。
基本上两个控制器对对象具有相同的引用,并且观察到对值的任何更改。
var app = angular.module('app', []);
app.factory('SharedState', SharedState);
function SharedState(){
var shared = this;
state = {variable: "search"};
shared.getState = function() {
return state;
}
return shared;
}
app.controller('AppCtrl', AppCtrl);
function AppCtrl(SharedState){
var appCtrl = this;
appCtrl.sharedState = SharedState.getState();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app">
<div ng-controller = "AppCtrl as ctrl1">
{{ctrl1.sharedState.variable}}
</div>
<div ng-controller = "AppCtrl as ctrl2">
<input type="search" ng-model = "ctrl2.sharedState.variable"/>
{{ctrl2.sharedState.variable}}
</div>
</div>
答案 1 :(得分:1)
Adricadar的回答非常好。
但我只是想张贴我写的那个:
var postData ={
'file_path' : "https://s3-us-west-2.amazonaws.com/ps/eams/6-48K.mxf",
'template_type' : "1",
'template_name' : "Basic Tests",
'job_type' : "0",
'user_note' : "my job",
'access-key-ID' : "AKAEBQ",
'access-key-SECRET' : "ZZHfO"
};
&#13;
var app = angular.module('app', []);
var appCtrl = app.controller('AppCtrl', AppCtrl);
appCtrl.$inject = ['ShareDataService'];
function AppCtrl(ShareDataService){
var appCtrl = this;
appCtrl.variable = "search";
appCtrl.setSearchQuery = function () {
ShareDataService.setSearchQuery(appCtrl.variable);
}
appCtrl.getSearchQuery = function () {
return ShareDataService.getSearchQuery();
}
}
var sharedDataService = app.service('ShareDataService',ShareData);
function ShareData(){
var shareDataService = this;
shareDataService.searchQuery = "";
shareDataService.getSearchQuery = function(){
return shareDataService.searchQuery;
}
shareDataService.setSearchQuery = function(searchQuery){
shareDataService.searchQuery = searchQuery;
}
}
&#13;
逻辑是: