亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將$ scope注入角度服務函數()

將$ scope注入角度服務函數()

largeQ 2019-07-29 16:34:47
將$ 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;});


查看完整回答
反對 回復 2019-07-29
?
侃侃爾雅

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');}]);


查看完整回答
反對 回復 2019-07-29
  • 3 回答
  • 0 關注
  • 619 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號