AngularJS app中不替换对象的属性值

时间:2015-09-23 06:48:41

标签: javascript angularjs

app.js是:

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"}而不是{&#34;名称&#34;:&#34; xyz&#34;}。为什么name的价值未被替换,即使setName(){{student}} index.html之前被调用了两次?

1 个答案:

答案 0 :(得分:1)

你有一个拼写错误:ng-contoller =“ChildController”应该 ng-cont r oller

如果解决这个问题 - 所有工作

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>

相关问题