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/