【问题标题】:Angular ng-submit only allow function in scopeAngular ng-submit 只允许范围内的函数
【发布时间】:2015-11-16 05:31:44
【问题描述】:

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

【问题讨论】:

  • 不应该是vm.test2 = test2 吗?
  • 是的,这是一个错字,不错
  • 将此作为答案

标签: javascript angularjs html submit


【解决方案1】:

一个不错的选择是将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>

【讨论】:

    【解决方案2】:

    当您在控制器代码中使用 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>
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-13
        • 2021-11-26
        • 2013-11-03
        • 2017-08-31
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多