[英]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未定义,以上代码显然会出错。
我读过某个地方 ,您需要获取正在使用控制器的元素ID,然后从中调用angular函数。 即:
angular.element(document.getElementById('formHome')).scope().angularFn(obj);
但是检查console.log(angular.element(document.getElementById('formHome')).scope)
似乎指向angular.js库而不是控制器,因此,调用angularFn函数也是未定义的。
那么,您如何能够从普通的旧JS函数中调用控制器函数?
您可以使用controllerAs
语法。 约定是您不应在控制器中使用$scope
将变量和函数分配给模板。
Java脚本
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()
从控制器访问函数或变量。
<form role="form" id="formHome">
<div ng-click="vm.angularFn(someobject)">
HTML Elements Here...
</div>
</form>
为什么在$scope
使用controllerAs
http://codetunnel.io/angularjs-controller-as-or-scope/
https://toddmotto.com/no-scope-soup-bind-to-controller-angularjs/
在这种情况下,作用域是一个函数,因此您需要这样做
console.log(angular.element(document.getElementById('formHome')).scope());
和
angular.element(document.getElementById('formHome')).scope().angularFn();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.