javascript - 为什么 $scope 在 Angular 1.6.1 中不起作用?

标签 javascript angularjs angularjs-scope this

背景

遵循 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>

有两种预期行为应该发生和不会发生:

  1. 当我点击提交时,我应该在控制台中看到 "Received submit order"但我不这么认为。
  2. input当我加载页面时,元素应该初始化为 4。

如果我使用var self = this;,这两种行为都会发生欺骗并替换所有提到的 $scopeself .

问题:

  1. 为什么这不起作用?我是否错过了一些结束?

最佳答案

您正在使用 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/

相关文章:

Javascript 命名空间声明

javascript - Angularjs ng-if 不工作

javascript - 在 JavaScript 中渲染期间缩小文件

javascript - Angular Strap Datepicker : Inconsistent timestamps returned, UTC +0 vs UTC +12 小时

javascript - 为什么两个$scopes同时更新,重复数据

javascript - 最好的开源 JavaScript 树?

javascript - 脚本错误 JavaScript 运行时错误 : Object doesn't support property or method 'row' with datatables plugin

javascript - 从 Angular Directive(指令)将多个参数传递给 Controller ​​函数

AngularJS : Isolating scope in a directive with transclude set to true

javascript - 如何永久禁用 Android 浏览器缓存?