2016-03-31 58 views
0

我正在用Ionic & Cordova创建一个照片编辑应用程序。我在网上读到,可以获得AngularJS变量并在JS中使用它们。但是,我尝试过了,我在控制台得到一个错误: app.js:1271遗漏的类型错误:$(...)范围不是一个函数如何从AngularJS获取变量并在javascript中使用它们?

这里是我的代码:

//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"); 
      }); 
+0

你能展示更多的代码吗?这是在控制器还是服务?这可能只是因为你没有将$ scope定义为依赖项。 – Dexter

+1

请在下面看到我的回答 –

回答

1

如果你的jQuery资源引用您的angualrjs资源引用后,您会收到此错误,角度切换到角jqlite,因而jQuery选择不知道.scope()

我创建了以下三个jsfiddles来证明,例如3将在控制台中有错误:

Example1:没有jQuery的 - 如果没有jQuery是引用您必须使用角度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是包括前角 - 使用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); 
} 
+0

好的。谢谢你的回答,但我会检查我的脚本。正如我所说,我使用Ionic Framework进行编码,所以在索引页面中进行引用。无论如何,我一定会查看并回复你 –

相关问题