search

Home  >  Q&A  >  body text

javascript - The difference between value and constant in angularjs (mainly the question of whether it can be modified)

Looking up the difference between angularjs global variables value and constant on the Internet, the answers are basically the same
1. Value cannot be injected in config, but constant can
2. Value can be modified, but constant cannot Modification, generally use constant directly to configure some data that needs to be used frequently.

There is nothing wrong with the first point, but what does the second point mean that this constant cannot be modified? What cannot be modified

<!DOCTYPE html>
<html lang="en" ng-app="myapp" >
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="base/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('myapp', []);
    app.constant('myConstant', { "value1": "林炳文", "value2": "hello world", value3: 1 });
    app.controller('myCtrl1', function ($scope, myConstant) {
        $scope.onclick1 = function () {
            $scope.value1 = myConstant.value1 + (++myConstant.value3);
            myConstant.value1 = $scope.value1;
            myConstant.value2 = $scope.value1;
        };
    });
    app.controller('myCtrl2', function ($scope, myConstant) {
        $scope.onclick2 = function () {
            $scope.value2 = myConstant.value2 + (++myConstant.value3);
            myConstant.value1 = $scope.value2;
            myConstant.value2 = $scope.value2;
        };
    });
</script>

</head>

    <body>
            <p ng-controller="myCtrl1">
                    <button ng-click="onclick1()">请点击我1</button>
            {{value1}}
    
</p>
        <p ng-controller="myCtrl2">
                <button ng-click="onclick2()">请点击我2</button>
              {{value2}}
    </p>
</body>

</html>
I wrote a small demo. It is obvious that the constant variable in it can be modified (I am testing an object here, and it can also be modified if it is replaced by a variable value). I don’t know if it’s me. I misunderstood it or wrote it in the wrong place. What is this so-called inability to modify?

曾经蜡笔没有小新曾经蜡笔没有小新2750 days ago1165

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-06-08 11:04:13

    angular.module('myApp', [])
    .constant('PI', '3.1415926')
    .config(function(PI) {})
    .value('name','Zhang San')

    constant is equivalent to a constant. Constant can be injected during config, but value cannot

    reply
    0
  • Cancelreply