我有一个主 js 文件, Controller 中有 watch -
(function () {
'use strict';
angular
.module('mainmodule')
.controller('file1Ctrl', file1Ctrl);
file1Ctrl.$inject = ['$scope','data'];
function VendorDetailCtrl($scope,data){
var vd = this;
vd.data.id = data.id;
activate();
function activate() {
$scope.$watch("vd.data.id", function (newValue, oldValue) {
if (newValue !== oldValue) {
callmainfunction();
}
});
}
})();
然后我在另一个 js 文件中有另一个指令 -
(function () {
'use strict';
angular
.module('mainmodule')
.directive('file2', file2)
function file2() {
var directive = {
restrict: 'E',
templateUrl: 'file2.html',
scope: {
data: '=',
},
controller: ['$scope',file2Ctrl],
controllerAs: 'vm',
bindToController: true
}
return directive;
function file2Ctrl($scope, file2Ctrl) {
var vm = this;
activate();
function activate(){
neededfunc();
}
function neededfunc(){
//do something
}
})();
我需要在第一个js文件中调用 watch 中的neededfunc()
。我什至尝试在指令中添加监视,但它仅在页面重新加载时触发,并且我需要它在单击按钮 Submit()
后运行。当我点击按钮 Submit()
时, watch 就会被触发。所以我需要知道如何在 watch 中使用该函数,或者当 id
值更改时是否有其他方法可以调用该函数。
最佳答案
向 $scope.$root 添加函数有帮助。以下是代码 -
// Declare the function
$scope.$root.neededFunction = function(){
//Do Something here
}
//Call the function
$scope.$root.neededFunction();
关于javascript - 将js文件中的指令函数加载到另一个 Controller js文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307564/