AngularJS将变量从服务绑定到控制器
我可以只将变量(而不是对象)从服务绑定到控制器吗 对于绑定对象,它可以工作(从):AngularJS将变量从服务绑定到控制器,angularjs,angularjs-scope,angularjs-service,Angularjs,Angularjs Scope,Angularjs Service,我可以只将变量(而不是对象)从服务绑定到控制器吗 对于绑定对象,它可以工作(从): 第一控制器 第二控制器 app.service('dataService',function()){ 该模型={ “prop1”:“, “建议2”:” }; }); 应用程序控制器('myCtrl1',函数($scope,dataService){ $scope.model1=dataService.model; }); app.controller('myCtrl2',函数($scope,dataServic
第一控制器
第二控制器
app.service('dataService',function()){
该模型={
“prop1”:“,
“建议2”:”
};
});
应用程序控制器('myCtrl1',函数($scope,dataService){
$scope.model1=dataService.model;
});
app.controller('myCtrl2',函数($scope,dataService){
$scope.model2=dataService.model;
});
但我只需要一个变量(不是具有属性的对象)
第一控制器
第二控制器
app.service('dataService',function()){
this.variable='';
});
应用程序控制器('myCtrl1',函数($scope,dataService){
$scope.variable1=dataService.variable;
});
app.controller('myCtrl2',函数($scope,dataService){
$scope.variable2=dataService.variable;
});
它不起作用。为什么?
有没有很好的方法(没有只有一个属性的对象或没有
$watch
)呢?您必须使用这样的对象:
您必须使用这样的对象:
它将作用域变量设置为
dataService
对象引用,并将ng model
属性设置为reference属性
JS
HTML
第一控制器
第二控制器
ng型号的经验法则是始终包含一个“点”
.将作用域变量设置为
dataService
对象引用,将ng model
属性设置为reference属性
JS
HTML
第一控制器
第二控制器
ng型号的经验法则是始终包含一个“点”
.它是一个具有一个属性的对象(如果我只需要一个变量,则解决方案有点难看,但我可能没有其他选择)。它是一个具有一个属性的对象(如果我只需要一个变量,则解决方案有点难看,但我可能没有其他选择)。
<div ng-controller="myCtrl1">
1st Controller
<input type="text" ng-model="model1.prop1"/>
<input type="text" ng-model="model1.prop2"/>
</div>
<div ng-controller="myCtrl2">
2nd Controller
<input type="text" ng-model="model2.prop1"/>
<input type="text" ng-model="model2.prop2"/>
</div>
app.service('dataService', function() {
this.model = {
'prop1': '',
'prop2': ''
};
});
app.controller('myCtrl1', function($scope, dataService) {
$scope.model1 = dataService.model;
});
app.controller('myCtrl2', function($scope, dataService) {
$scope.model2 = dataService.model;
});
<div ng-controller="myCtrl1">
1st Controller
<input type="text" ng-model="variable1"/>
</div>
<div ng-controller="myCtrl2">
2nd Controller
<input type="text" ng-model="variable2"/>
</div>
app.service('dataService', function() {
this.variable = '';
});
app.controller('myCtrl1', function($scope, dataService) {
$scope.variable1 = dataService.variable;
});
app.controller('myCtrl2', function($scope, dataService) {
$scope.variable2 = dataService.variable;
});
app.service('dataService', function() {
this.variable = {a:''};
});
app.controller('myCtrl1', function($scope, dataService) {
$scope.ds1 = dataService;
});
app.controller('myCtrl2', function($scope, dataService) {
$scope.ds2 = dataService;
});
<div ng-controller="myCtrl1">
1st Controller
<input type="text" ng-model="ds1.variable"/>
</div>
<div ng-controller="myCtrl2">
2nd Controller
<input type="text" ng-model="ds2.variable"/>
</div>