AngularJS 从 Javascript 调用控制器函数

AngularJS Call Controller Function from Javascript

在Angular SPA应用程序中,您通常会在app.js

中有以下代码
var app = angular.module('MyApp', ['ngRoute']);

app.config(function ($routeProvider){
  $routeProvider.when("/home", {
        controller: "homeCtrl",
        templateUrl: "app/views/home.html"
    });
});

HTML (home.html)

<form role="form" id="formHome">
  <div>
    HTML Elements Here...
  </div>
</form>

和 homeCtrl:

'use strict';
app.controller('homeCtrl', ['$scope', '$location', function($scope, $location){

  $scope.angularFn = function(obj){
    // Do Some Stuff with obj.
  }

  function myTestFunction(){
    // Call $scope.angularFn here.
    var obj = {name: 'John', team: 'Nissan'};
   $scope.angularFn(obj);
  }

}]);

上面的代码显然会出错,因为 $scope.angularFn 未定义。

我读到 somewhere 您需要获取正在使用控制器的元素 ID,并从中调用 angular 函数。即:

angular.element(document.getElementById('formHome')).scope().angularFn(obj);

但是检查 console.log(angular.element(document.getElementById('formHome')).scope)

似乎指向 angular.js 库,而不是控制器,因此调用 angularFn 函数也是未定义的。

那么,如何从普通的旧 JS 函数中调用控制器函数?

在那种情况下作用域是一个函数,所以你需要这样做

console.log(angular.element(document.getElementById('formHome')).scope());

angular.element(document.getElementById('formHome')).scope().angularFn();

您可以使用 controllerAs 语法。约定是您不应在控制器中使用 $scope 将变量和函数分配给模板。

Javascript

var app = angular.module('MyApp', ['ngRoute']);

app.config(function ($routeProvider){
  $routeProvider.when("/home", {
        controller: "homeCtrl",
        controllerAs: 'vm', // note this is added to route
        templateUrl: "app/views/home.html"
    });
});

'use strict';
app.controller('homeCtrl', ['$location', function($location){
  // this will be equal to the controller and will be same as $scope
  // using $scope is not recommended and should be used as follows
  // quick google on why not to use scope will give you plenty of explanation
  var vm = this;

  vm.angularFn = function(obj){
    // Do Some Stuff with obj.
  }

  function myTestFunction(){
    var obj = {name: 'John', team: 'Nissan'};
    vm.angularFn(obj);
  }

}]);

模板:

然后您可以使用 vm.variableNamevm.FunctionName()

从控制器访问函数或变量
<form role="form" id="formHome">
  <div ng-click="vm.angularFn(someobject)">
    HTML Elements Here...
  </div>
</form>

为什么使用 controllerAs 而不是 $scope

http://codetunnel.io/angularjs-controller-as-or-scope/

https://toddmotto.com/no-scope-soup-bind-to-controller-angularjs/