gpt4 book ai didi

javascript - 'this' 在 AngularJS Controller 中到底意味着什么?

转载 作者:行者123 更新时间:2023-11-28 18:27:48 25 4
gpt4 key购买 nike

index.html

 <body ng-controller="StoreController as s">
<h1 ng-click="s.changeValFunc()">{{s.carname}}</h1>
<h2>{{s.carname}}</h2>
</body>

app.js

var app = angular.module('store', []);
app.controller('StoreController', function() {
this.carname = "Volvo";
this.changeValFunc = function(){
this.carname="BMW";
}
});

点击 h1 标签会将 h1 和 h2 的 {{carname}} 更改为 BMW。难道“this”指的是当前被点击的元素吗?我对如何在 View 之间共享 Controller 属性感到困惑。

最佳答案

Controller 函数通过new实例化。这意味着它的工作原理如下:

function StoreController() {
this.carname = "Volvo";
this.changeValFunc = function () {
this.carname="BMW";
}
};

var s = new StoreController();

console.log(s.carname); // Volvo

View 中的 s 是对实例化的 StoreController 的引用,它具有这些属性,因为您将它们放在构造函数中。您可能想查看How does the "this" keyword work?了解详情。

关于javascript - 'this' 在 AngularJS Controller 中到底意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com