2014-07-13 31 views
0

嘗試將外部指令和服務導入到我的角度應用程序。還沒有弄明白。仍在學習Angular。嘗試處理外部服務/指令,獲取未被捕獲的對象

我有一個簡單的應用程序:

var app = angular.module('imageRepo', ['fileModelDirective','fileUploadService']); 

    app.controller('indexController',['$scope', 'fileUpload', function ($scope, fileUpload) 
    { 
     $scope.uploadFile = function (tag) { 
      var file = $scope.myFile; 
      console.log("File: " + JSON.stringify(file) + "\nTag: " + tag); 
      fileUpload.uploadFileToUrl(file,tag,'/api/file'); 
     } 
    }]) 

我的服務:

angular.module('fileUploadService'). 
service('fileUpload', ['$http', function ($http) { 
    this.uploadFileToUrl = function (file,tag,uploadUrl) { 
    var fd = new FormData(); 
    fd.append('file', file); 
    fd.append('tag',tag); 
    $http.post(uploadUrl,fd, { 
     transformRequest: angular.identity, 
     headers: {'Content-Type':undefined} 
    }). 
    success(function() { 
     alert('SUCCESS!!!'); 
    }). 
    error(function() { 
     alert("ERROR!!!"); 
    }); 
} 
}]); 

最後我的指令:

angular.module('fileModelDirective'). 
directive('fileModel',['$parse', function($parse) { 
    return { 
     restrict: 'A', 
     link: function (scope, element, attributes) { 
      var model = $parse(attributes.fileModel); 
      var modelSetter = model.assign; 

      element.bind('change', function() { 
       scope.$apply(function() { 
        modelSetter(scope, element[0].files[0]); 
      }); 
     }); 
    } 
    } 
}]); 

正如我在加載到我的瀏覽器(Chrome)我得到「未被捕獲的對象」。這裏有一些明顯的錯誤,但作爲角度的noob我找不到它。

回答

0

我認爲你的錯誤可能來自聲明模塊時缺少的參數。你需要指定它的依賴(即使沒有):

var module = angular.module('fileUploadService',[]); 

我經常組織我的模塊,像這樣:

var app = angular.module('myapp',['controllers', 'directives']); 
var controllers= angular.module('controllers',[]); 

controllers.controller('someController', function($scope) { 

}); 

controllers.controller('anotherController', function($scope) { 

}); 
+0

謝謝!這解決了它! – jne

+0

沒問題,別忘了接受答案:) – cluxton

相關問題