我在我的JS文件中定义一个变量(突出显示器),并希望在角度控制器中使用它(我在同一个JS文件中定义)。控制器无法识别它。
我尝试了几种方法,但都失败了,我现在有点困惑。 我只粘贴代码的相关部分和一般结构。
(function() {
"use strict";
var highlighter;
window.highlighter = highlighter;
})();
(function(angular) {
'use strict';
angular.module('myApp', ['ui.bootstrap'])
.controller('Controller', function($scope, $window, $http) {
$scope.highlighter1 = function(side, string, load) {
highlighter.deserialize(string);
};
})
})(window.angular);
答案 0 :(得分:1)
您正在将highlighter
的范围限制为您使用IIFE编写的匿名函数。为了使其范围在角度代码范围内可用,请将其设置为全局,如下所示:
var highlighter;
window.highlighter = highlighter;
(function(angular) {
'use strict';
angular.module('myApp', ['ui.bootstrap'])
.controller('Controller', function($scope, $window, $http) {
$scope.highlighter1 = function(side, string, load) {
highlighter.deserialize(string);
};
})
})(window.angular);
答案 1 :(得分:0)
您是否尝试在localstorage中设置它并对其进行检索(它更持久)..:
(function() {
"use strict";
var highlighter;
localStorage.setItem('authorizationData', JSON.stringify(highlighter));
// window.highlighter = highlighter;
})();
(function(angular) {
'use strict';
angular.module('myApp', ['ui.bootstrap'])
.controller('Controller', function($scope, $window, $http,exampleService) {
var fromLocalStorage=exampleService.Get();
$scope.highlighter1 = function(side, string, load) {
highlighter.deserialize(string);
};
})
})(window.angular);
"use strict";
angular
.module("myApp")
.factory("exampleService", [ "$q", "localStorageService"
function ( $q, localStorageService) {
// Public Method
return {
Set: function (value) {
localStorageService.remove("authorizationData");
localStorageService.set("authorizationData",value);
return localStorageService.get("authorizationData");
},
Get: function () {
return localStorageService.get("authorizationData");
},
Remove: function () {
localStorageService.remove("authorizationData");
}
};
}]);