我正在使用 Ionic 和 Cordova 创建一个照片编辑应用程序。我在网上读到可以获取 AngularJS 变量并在 JS 中使用它们。但我尝试了一下,控制台中出现错误: app.js:1271 未捕获类型错误:$(...).scope 不是函数
这是我的代码:
//Loading the variable from AngularJS
window.onload = function() {
var sources = {
yoda: $('[ng-controller="SecureController"]').scope().pictureUrl
};
loadImages(sources, initStage);
};
//Using ngCordova to capture the image and set the image link to $scope.pictureUrl. *This part works*
$cordovaCamera.getPicture(options)
.then(function(imageData) {
syncArray.$add({image: imageData});
$scope.pictureUrl= 'data:image/jpeg:base64,' + data
.then(function() {
alert("Image has been uploaded");
});
最佳答案
如果您的 jQuery 资源引用位于 angualrjs 资源引用之后,Angualrjs 资源引用之后,Angular 切换到 Angular jqlite,您将收到此错误,因此 jQuery 选择器不知道 .scope()
我创建了以下三个jsfiddles来演示,示例3将在控制台中出现错误:
Example1 :没有 Jquery - 如果没有引用 jquery,则必须使用 Angular jqlite
HTML:
<div id="myDiv" ng-controller="SecureController">
<h1>{{pictureUrl}}</h1>
</div>
JS:
var myApp = angular.module('application', []);
myApp.controller('SecureController', ['$scope', function($scope) {
$scope.pictureUrl = 'this is a test url';
}]);
window.onload = function() {
var sources = {
yoda: angular.element(document.getElementById('myDiv')).scope().pictureUrl
};
console.log(sources.yoda);
alert(sources.yoda);
}
Example2 :jQuery 包含在 Angular 之前 - 使用 jQuery 选择器
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<div id="myDiv" ng-controller="SecureController">
<h1>{{pictureUrl}}</h1>
</div>
JS:
var myApp = angular.module('application', []);
myApp.controller('SecureController', ['$scope', function($scope) {
$scope.pictureUrl = 'this is a test url';
}]);
window.onload = function() {
var sources = {
yoda: $('#myDiv').scope().pictureUrl
};
console.log(sources.yoda);
alert(sources.yoda);
}
Example3 :jQuery 包含在 angaular 之后 - 您将收到 Uncaught TypeError: $(...).scope is not a function
错误
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="myDiv" ng-controller="SecureController">
<h1>{{pictureUrl}}</h1>
</div>
JS:
var myApp = angular.module('application', []);
myApp.controller('SecureController', ['$scope', function($scope) {
$scope.pictureUrl = 'this is a test url';
}]);
window.onload = function() {
var sources = {
yoda: $('#myDiv').scope().pictureUrl
};
console.log(sources.yoda);
alert(sources.yoda);
}
关于javascript - 如何从 AngularJS 获取变量并在 javascript 中使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332018/