2016-03-31 55 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進行編碼,所以在索引頁面中進行引用。無論如何,我一定會查看並回復你 –

相關問題