在 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您需要获取正在使用 Controller 的元素 ID,并从中调用 Angular 函数。即:
angular.element(document.getElementById('formHome')).scope().angularFn(obj);
但是检查console.log(angular.element(document.getElementById('formHome')).scope)
似乎指向 angular.js 库,而不是 Controller ,因此,调用 angularFn 函数也是未定义的。
那么,如何从普通的旧 JS 函数中调用 Controller 函数呢?
最佳答案
您可以使用controllerAs
语法。约定是您不应在 Controller 中使用 $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.variableName
或vm.FunctionName()
从 Controller 访问函数或变量
<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/
关于javascript - AngularJS 从 Javascript 调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34782487/