对象的属性值在AngularJS应用中是不会被替换的

Value of property of an object is not replaced in AngularJS app

本文关键字:替换 应用 属性 AngularJS 对象      更新时间:2023-09-26

app.js is:

var app = angular.module('ControllerHierarchyAkaScopesWithinScopes',[]);
app.controller('ParentController',function($scope){ // this $scope is controller specific
    $scope.student = {name:"abc"};
});
app.controller('ChildController',function($scope){ // this $scope is controller specific
    $scope.setName = function(){
        $scope.student.name = "xyz";
    };
});

index.html为:

<html ng-app="ControllerHierarchyAkaScopesWithinScopes">
    <head>
        <script src="angular.js" type="text/javascript"></script>
        <script src="ControllerHierarchy.js" type="text/javascript"></script>
    </head>
    <body>
        <div ng-controller="ParentController">
            <div ng-contoller="ChildController">
                <a ng-click="setName()">click this to change value of $scope.student.name</a>
                {{setName()}}
                {{student}} 
            </div>
        </div>
    </body>
</html>

当我访问index.html时,它显示{"name":"abc"}而不是{"name":"xyz"}。

为什么index.htmlsetName(){{student}}之前调用了两次,name的值却没有被替换?

这里有个错字:ng- controller ="ChildController"应该是ng-controller

如果修复这个-所有工作

var app = angular.module('ControllerHierarchyAkaScopesWithinScopes',[]);
app.controller('ParentController',function($scope){ // this $scope is controller specific
    $scope.student = {name:"abc"};
});
app.controller('ChildController',function($scope){ // this $scope is controller specific
      $scope.setName = function(){
      console.log('setName', $scope);
        $scope.student.name = "xyz";
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="ControllerHierarchyAkaScopesWithinScopes">
        <div ng-controller="ParentController">
            <div ng-controller="ChildController">
                <a  ng-click="setName()">click this to change value of $scope.student.name</a>
                {{student}} 
            </div>
        </div>
    </div>