我在AngularJS中创建了一个具有 Skinny AngularJS Controllers 的应用程序。该应用程序工作正常,但问题是我有一个$scope.submit
方法,我需要通过该方法将值设置为this.name
,并通过this.getDetails
方法我需要获取值,但不幸的是,该值未与this.name
变量绑定。
任何人都可以告诉我一些解决方案吗
脚本
var app = angular.module('myApp', []);
app.controller('ControllerOne', function ($scope) {
this.getDetails = function () {
return this.name;
};
$scope.submit = function () {
this.name = "Messi";
};
});
答案 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.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