简体   繁体   English

为什么我不能更改变量的值? 角度的

[英]Why Can't I change value of the variable? Angular

I made a service that stores a variable I use in two controllers. 我提供了一个服务,该服务存储在两个控制器中使用的变量。

function CommonVariables() {
    var number = 3;

    return {
        setNumber: function(num) {
            number = num;
        },
        getNumber: function() {
            return number;
        }
    }
};

The problem is that I can get this variable like this: 问题是我可以像这样获取此变量:

this.number = CommonVariables.getNumber();

I want it to be changed like this: 我希望这样更改:

<input class="numInput" ng-model="Ctrl.number">

in Js: 在Js中:

function Controller(CommonVariables) {
    this.number = CommonVariables.getNumber();
    CommonVariables.setNumber(this.number);
}

But I can't and don't understand why 但是我不知道为什么

You need to not only update the variable in the controller, but also send that update back to the service, from which it can be shared to any other part of your application. 您不仅需要更新控制器中的变量,还需要将该更新发送回服务,然后可以从中将其共享到应用程序的任何其他部分。

===================================================== ================================================== ===

edit: working code for me - check your console logs as you run it: 编辑:为我工作的代码-运行时检查控制台日志:

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

You need to $watch the property number in the controller scope. 您需要$watch控制器作用域中的属性number

Inject $scope and use 注入$scope并使用

function Controller(CommonVariables, $scope) {

    $scope.$watch(angular.bind(this, function () {
        return this.number;
    }), function (newVal) {
        CommonVariables.setNumber(newVal);
    });
...

By looking at your code assuming you are using controller as syntax 通过查看代码(假设您使用controller as语法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM