背景
遵循 AngularJS tutorial on codeSchool 后阅读了一些 StackOverflow 问题后,我决定开始使用 $scope
为了避免必须定义 var self = this;
的麻烦变量。
问题
问题是 $scope
似乎没有绑定(bind)任何东西,当我使用它时没有任何作用。我不知道为什么,但如果我使用 var self = this;
变量我的代码将工作,即使在理论上(根据我所知道的)$scope
应该做同样的事情...
代码
假设我有一个页面,我想在其中显示大量数字列表。还假设我有分页,并且我希望每页的默认数字数量为 4。我们还假设在每次向服务器发出请求后,我再次将每页显示的数字数量设置为 4。
app.js
/*global angular, $http*/
(function() {
var app = angular.module("myNumbers", []);
app.directive("numberFilter", function() {
return {
restrict: "E",
templateUrl: "number-filter.html",
controller: function($scope, $http) {
$scope.filter = {
itemsPerPage: 4
};
$scope.makeRequest = function(numberList) {
console.log("Received submit order");
$http({
method: 'GET',
url: 'https://myNumberServer.com/api/v1/getPrimes',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function successCallback(response) {
numberList= response.data.entries;
$scope.totalPages = response.data.totalPages;
$scope.filter = {itemsPerPage: 4};
console.log("success!");
}, function errorCallback(response) {
console.log('Error: ' + response);
});
};
},
controllerAs: "filterCtrl"
};
});
})();
number-filter.html
<form ng-submit="filterCtrl.makeRequest(myNumbers.numberList)">
<div >
<label for="items_per_page-input">Items per page</label>
<input type="number" id="items_per_page-input" ng-model="filterCtrl.filter.itemsPerPage">
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
有两种预期行为应该发生和不会发生:
- 当我点击提交时,我应该在控制台中看到
"Received submit order"
但我不这么认为。 input
当我加载页面时,元素应该初始化为 4。
如果我使用var self = this;
,这两种行为都会发生欺骗并替换所有提到的 $scope
与 self
.
问题:
- 为什么这不起作用?我是否错过了一些结束?
最佳答案
您正在使用 controllerAs
语法,因此当您使用该语法时,您的模型需要分配给 Controller 对象本身,而不是 $scope
示例
controller: function($scope, $http) {
var vm = this; // always store reference of "this"
// use that reference instead of $scope
vm.filter = {
itemsPerPage: 4
};
vm.makeRequest = function(numberList) {
console.log("Received submit order");
$http({
method: 'GET',
url: 'https://myNumberServer.com/api/v1/getPrimes',
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function successCallback(response) {
numberList = response.data.entries;
vm.totalPages = response.data.totalPages;
vm.filter = {
itemsPerPage: 4
};
console.log("success!");
}, function errorCallback(response) {
console.log('Error: ' + response);
});
};
},
关于javascript - 为什么 $scope 在 Angular 1.6.1 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055224/