javascript - Angular ng-submit 只允许作用域内的函数

标签 javascript angularjs html submit

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

例如

这是 Controller

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('/');
}

最佳答案

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

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>

关于javascript - Angular ng-submit 只允许作用域内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32154411/

相关文章:

javascript - 使用 Node JS 连接到 Mongo DB 时出现 SyntaxError : await is only valid in async function,

javascript - 如何将 mvc Controller actionresult 参数传递给 angularjs Controller

html - 为什么 margin 不适用于组件,即使是用相对位置定义的组件

php - 如何在 PHP 中转义隐藏的表单值

javascript - 主干模型更改事件仅触发一次

javascript - 在 colorbox 内提交表单后重新加载 dataTable

php - 如何在 AngularJS 和 PHP 中获取最大数量的 JSON 记录作为响应

javascript - W3 CSS 动画

javascript - 通过用户输入更改 Cordova App 中的字体大小

android - AdMob 未在 ionic /Angular 应用中加载广告