将$ 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 关注
- 671 浏览
添加回答
举报
0/150
提交
取消
