我创建了一个服务,用于存储我在两个控制器中使用的变量。
function CommonVariables() {
var number = 3;
return {
setNumber: function(num) {
number = num;
},
getNumber: function() {
return number;
}
}
};
问题是我可以像这样得到这个变量:
this.number = CommonVariables.getNumber();
我希望它像这样改变:
<input class="numInput" ng-model="Ctrl.number">
在Js:
function Controller(CommonVariables) {
this.number = CommonVariables.getNumber();
CommonVariables.setNumber(this.number);
}
但我无法理解为什么
答案 0 :(得分:2)
您不仅需要更新控制器中的变量,还需要将该更新发送回服务,然后可以将该更新共享到应用程序的任何其他部分。
=============================================== ==
编辑:为我工作代码 - 在运行时检查控制台日志:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<body>
<div ng-app="myApp" ng-controller="Ctrl">
<input class="numInput" ng-model="number" ng-change="changeNumber()">
</div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("Ctrl", function(CommonVariables, $scope){
//this will initially set it as the same number as is stored in CommonVariables
$scope.number = CommonVariables.getNumber();
//this is the function that will actually send that number back to the service to update it there
$scope.changeNumber = function() {
console.log("Number set:", $scope.number);
CommonVariables.setNumber($scope.number)
console.log("Number retrieved after setting:", CommonVariables.getNumber());
}
})
.factory("CommonVariables", function(){
var number = 3;
return {
setNumber: function(num) {
number = num;
},
getNumber: function() {
return number;
}
}
})
</script>
答案 1 :(得分:0)
您需要$watch
控制器范围内的属性number
。
注入$scope
并使用
function Controller(CommonVariables, $scope) {
$scope.$watch(angular.bind(this, function () {
return this.number;
}), function (newVal) {
CommonVariables.setNumber(newVal);
});
...
通过查看代码,假设您使用controller as
语法