我正在做一个项目,同时使用Jquery和AngularJS。Jquery-主要针对已经可用的插件。Angular-便于处理表单和对象以及DOM操作。
我有一个插件(https://github.com/VinceG/twitter-bootstrap-wizard)其中自定义事件被定义为-onShow、onFinish、onNext等。当用户做某事时,这些事件会被触发。
如何从其中一个函数调用AngularJS函数?
来自插件的代码
$(document).ready(function() {
$('#rootwizard').bootstrapWizard({
tabClass: 'nav nav-pills',
onNext: function(tab, navigation, index) {
//I want to access the myFunction declared
//inside the AngularJS code and pass 'index' to it
}
});
});
AngularJS代码
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myFunction = function(index) {
// do something with index
}
});
实现这一点的最简单方法是从某个元素检索控制器的作用域,然后调用它的方法,如:
var myScope = angular.element($('#someElement')).scope();
myScope.doSomething(); // make sure you also invoke the $scope.$apply() to start the digest process.
但是,首先想想,这是你真正想做的吗,我觉得这种方式有点古怪,而且从长远来看,IMO混合jQuery和Angular也不是一件好事。。。
在ES6中,控制器可以定义为标准类。如果以这种方式定义它们,那么在角度之外导入和使用它们也很容易。
class MainController {
constructor(searchService) {
this.title = 'Hello World';
}
myFunction () {
// do things...
}
someOtherFunction () {
// do things...
}
}
export { MainController }
在app.js
(或其他)中
import { someFunction, someOtherFunction } from "web/static/js/MainController";
然后你可以用访问它
let result = someFunction();