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

标签 javascript angularjs model-view-controller controller angularjs-controller

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/

相关文章:

javascript - 无论如何从 form.submit() 返回 JSON

javascript - 动画栏仅在圆圈上可见 - svg

ios - 带有 UIViewController 和 Storyboard 的模型- View - Controller

用于短信和电子邮件通知服务的 C# 代码

javascript - React 读取 json 并将字段转换为字符串

javascript - 使用默认代码在 angularjs 中设置InfiniteScroll

javascript - 观察范围对象包含特殊字符作为键

php - HREF 向 Controller 发送参数并返回 View

angularjs - 为什么我得到错误模块在 JSFiddle 中不可用?

javascript - 没有指令的 AngularJS 图片上传预览