將$ scope注入角度服務(wù)函數(shù)()我有一個(gè)服務(wù):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;
}
}
}
};但是當(dāng)我打電話時(shí)save(),我無法訪問$scope,并得到ReferenceError: $scope is not defined。所以邏輯步驟(對我而言)是提供save()$scope,因此我還必須提供/注入它service。所以,如果我這樣做: .service('StudentService', [ '$http', '$scope',
function ($http, $scope) {我收到以下錯(cuò)誤:錯(cuò)誤:[$ injector:unpr]未知提供者:$ scopeProvider < - $ scope < - StudentService錯(cuò)誤中的鏈接(哇哇哇?。┳屛抑浪c注入器相關(guān),并且可能與js文件的聲明順序有關(guān)。我曾嘗試重新排序它們index.html,但我認(rèn)為它更簡單,例如我注入它們的方式。使用Angular-UI和Angular-UI-Router
3 回答

慕運(yùn)維8079593
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
$scope
您可以$watch
在控制器中實(shí)現(xiàn)a,而不是嘗試修改服務(wù)內(nèi)部,以便在服務(wù)上查看屬性以進(jìn)行更改,然后更新屬性$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; } }); }()); }]);
需要注意的一點(diǎn)是,在您的服務(wù)中,為了使students
屬性可見,它需要在Service對象上,或者this
像這樣:
this.students = $http.get(path).then(function (resp) { return resp.data;});

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