角度范围绑定

时间:2015-07-08 15:36:25

标签: javascript angularjs angularjs-scope

我跟随一本书,并使用此版本的Angular:https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js[1]

这是我的模板:

<div ng-controller="ParentController">
    <div ng-controller="ChildController">
        <a ng-click="sayHello()">Say hello</a>
    </div>
    {{ person }}
</div>

这是我的控制器代码:

app.controller('ParentController', function ($scope) {
    $scope.person = { greeted: false };

});

app.controller('ChildController', function ($scope) {
    $scope.sayHello = function () {
        $scope.person = { name: "Ari Lerner", greeted: true };
    }
});

我注意到我的代码并没有像预期的那样更新模板,除非我将sayHello方法更改为:

$scope.sayHello = function () {
    $scope.person.name = "Ari Lerner";
    $scope.person.greeted = true;
};

有关为什么会出现这种情况的任何见解?我假设更新人员会反映在DOM中。

使用1.4.2会产生相同的结果。

认为这些属性可能以某种方式被编入索引,我尝试了以下内容:

$scope.person.name = { greeted: true, name: "Ari Lerner" };

(切换问候和姓名)

狂野猜测:在我看来,Angular中的某些内容正在保留分配给$ scope.person并将$ scope.person设置为新对象的原始对象&#34;失去&#34;数据绑定。这是真的吗?

4 个答案:

答案 0 :(得分:2)

In AngularJS, scopes use prototypical inheritance from their parents.

Prototypical inheritance basically means that JavaScript will look at the parent scope if it doesn't find a property on the child scope.

So, when you do $scope.person.name = 'Ari Lerner', JavaScript looks at $scope, sees that it doesn't have a person property, then goes to its parent (the parent scope), sees that it has a person property, and assigns the name property of that to 'Ari'.

On the other hand, when you do $scope.person = { ... }, JavaScript doesn't care if the property exists or not - it simply carries out the assignment, ensuring that your $scope now has a person property. The problem here is that your child scope's person property now shadows the person property of the parent scope, which still has its original value. So, in the parent controller, person never changed.

For further reading, check this answer here:

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

答案 1 :(得分:0)

You are creating a child scope that prototypically inherits from its parent scope. This is the case unless you are using an isolate scope (directive).

For a really great explanation, see here What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

答案 2 :(得分:0)

正如其他人所说,这是因为你的范围。

例如,如果要在childScope中创建新对象,则执行$scope.someObject = {};。 现在,JavaScript无法知道

之间的区别

$scope.someNewObject = {};

$scope.person = {};

因为你只是在你的childscope上分配一个新对象。 另一种表示法有效,因为通过抓取$scope.person.attribute = ... JavaScript知道,person对象已经存在。它开始在你的childscope中查找这个对象,在那里找不到它,转到parentcope并在那里找到它并设置属性。

总之您必须使用$scope.person.attribute,或者使用$scope.$parent.person = {};

答案 3 :(得分:-2)

To edit $scope.person from the childController (child scope) use $scope.$parent like so...

app.controller('ChildController', function ($scope) {
    $scope.sayHello = function () {
        $scope.$parent.person = { name: "Ari Lerner", greeted: true };
    }
});