Angular ng-submit 只允许范围内的函数

Angular ng-submit only allow function in scope

在 angular js 中,html 是否可以访问未在 $scope 中定义的函数?

例如

这是控制器

function TestController($location, $scope){
    var vm = this;
    vm.test2 = test2

    $scope.test1 = function(){
      console.log("testing");
    };


    function test2(){
      console.log("what is going on");

    }

  }

这是html有效的

<div ng-controller="TestController" id="whatup">
  <form ng-submit="test1()">
      <input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="email"></input>
      <input type="submit">
  </form>
</div>

如果我将 test1() 更改为 test2() ,代码将不再有效,这是有原因的吗?

我是否必须通过其他方式公开 test2(),例如在路由中定义它?

function config($routeProvider){
    $routeProvider.when('/test', {
    controller: 'TestController',
    controllerAs: 'vm',
    templateUrl: 'templates/test.html'
    }).otherwise('/');
}

当您在控制器代码中使用 this.propOrMethod 时,您可以使用 ControllerAs 语法在视图中获取它:

<div ng-controller="TestController as testController">
   {{testController.propOrMethod}}
</div>

推荐:

不要自己使用 $scope waythis.propOrMethod way 这两种方法来混淆您的代码。无论如何,如果你喜欢在不同的 div 中使用它们,你可以同时使用它们:

<div ng-controller="TestController as testController">
   {{testController.propOrMethod}} <!-- this.propOrMethod-->
</div>
<div ng-controller="TestController">
   {{propOrMethod}} <!--$scope.propOrMethod-->
</div>

一个不错的选择是将 test2 函数直接创建到控制器变量中:

function TestController($location, $scope, Authentication){
  var vm = this;

  $scope.test1 = function(){
    console.log("testing");
  };


  vm.test2 = function (){
    console.log("what is going on");
  };
}

你也可以这样调整你html:

<div ng-controller="TestController as vm" id="whatup">
  <form ng-submit="vm.test2()">
      <input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="email"></input>
      <input type="submit">
  </form>
</div>

您需要删除 (),因为它在 this 中执行,而应该是 fn

vm.test2 = test2()更改为vm.test2 = test2