在angularjs中的$ scope方法下,没有使用this.name绑定值

时间:2015-02-27 10:30:34

标签: javascript angularjs angularjs-scope

我在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";
    };
});

2 个答案:

答案 0 :(得分:1)

不同的背景:

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";
    };
});

答案 1 :(得分:1)

问题在于$scope.submitthis指的是$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

的原因