將$ scope注入角度服務函數()我有一個服務:angular.module('cfd')
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = 'data/people/students.json';
var students = $http.get(path).then(function (resp) {
return resp.data;
});
//save method create a new student if not already exists
//else update the existing object
this.save = function (student) {
if (student.id == null) {
//if this is new student, add it in students array
$scope.students.push(student);
} else {
//for existing student, find this student using id
//and update it.
for (i in students) {
if (students[i].id == student.id) {
students[i] = student;
}
}
}
};但是當我打電話時save(),我無法訪問$scope,并得到ReferenceError: $scope is not defined。所以邏輯步驟(對我而言)是提供save()$scope,因此我還必須提供/注入它service。所以,如果我這樣做: .service('StudentService', [ '$http', '$scope',
function ($http, $scope) {我收到以下錯誤:錯誤:[$ injector:unpr]未知提供者:$ scopeProvider < - $ scope < - StudentService錯誤中的鏈接(哇哇哇!)讓我知道它與注入器相關,并且可能與js文件的聲明順序有關。我曾嘗試重新排序它們index.html,但我認為它更簡單,例如我注入它們的方式。使用Angular-UI和Angular-UI-Router
3 回答

慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
$scope
您可以$watch
在控制器中實現a,而不是嘗試修改服務內部,以便在服務上查看屬性以進行更改,然后更新屬性$scope
。以下是您可以在控制器中嘗試的示例:
angular.module('cfd') .controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) { $scope.students = null; (function () { $scope.$watch(function () { return StudentService.students; }, function (newVal, oldVal) { if ( newValue !== oldValue ) { $scope.students = newVal; } }); }()); }]);
需要注意的一點是,在您的服務中,為了使students
屬性可見,它需要在Service對象上,或者this
像這樣:
this.students = $http.get(path).then(function (resp) { return resp.data;});

侃侃爾雅
TA貢獻1801條經驗 獲得超16個贊
好吧(很長一段)...如果你堅持要$scope
在服務中訪問,你可以:
創建一個getter / setter服務
ngapp.factory('Scopes', function (){ var mem = {}; return { store: function (key, value) { mem[key] = value; }, get: function (key) { return mem[key]; } };});
注入它并將控制器范圍存儲在其中
ngapp.controller('myCtrl', ['$scope', 'Scopes', function($scope, Scopes) { Scopes.store('myCtrl', $scope);}]);
現在,將范圍放在另一個服務中
ngapp.factory('getRoute', ['Scopes', '$http', function(Scopes, $http){ // there you are var $scope = Scopes.get('myCtrl');}]);
- 3 回答
- 0 關注
- 619 瀏覽
添加回答
舉報
0/150
提交
取消