在 angularjs 中的 $scope 方法下,值未与 this.name 绑定

value not getting binded with this.name under a $scope method in angularjs

我在 AngularJS 中创建了一个具有 Skinny AngularJS Controllers 的应用程序。该应用程序工作正常,但问题是我有一个 $scope.submit 方法,我需要通过该方法将值设置为 this.name,并通过 this.getDetails 方法我需要获取该值,但不幸的是,该值未与 this.name 变量绑定。

谁能告诉我一些解决方案

JSFiddle

脚本

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {

    this.getDetails = function () {
        return this.name;
    };

    $scope.submit = function () {
        this.name = "Messi";
    };
});

不同的上下文:

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {
    var _this = this;

    this.getDetails = function () {
        return _this.name;
    };

    $scope.submit = function () {
        _this.name = "Messi";
    };
});

问题是在 $scope.submit 中,this 指的是 $scope,而不是您的控制器。 例如,这将起作用:

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {
    var vm = this;
    vm.getDetails = function () {
        return vm.name;
    };

    $scope.submit = function () {
        vm.name = "Messi";
    };
});

IMO,你应该避免混合使用 $scope 和 this,而只使用 this。不要忘记在 HTML 中使用 one.submit() :

var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {
    this.getDetails = function () {
        return this.name;
    };

    this.submit = function () {
        this.name = "Messi";
    };
});

编辑:查看本指南,了解使用变量存储 this 的好处以及我将其命名为 vm https://github.com/johnpapa/angularjs-styleguide#controllers

的原因