Angular: Not able to access variables in controller using service

亡梦爱人 提交于 2019-12-24 01:20:10

问题


I am trying to share a variable between a controller and a function. But i get an error from the controller, saying this:

TypeError: Cannot read property 'getSet' of undefined 

I have gone through numerous tutorials, but don't know where am I going wrong. My service code is like this:

app.service('shareData', function() {

    var selected = ["plz", "print", "something"];

    var putSet = function(set) {
        selected = set;
    };

    var getSet = function() {
        return selected;
    };

    return {
        putSet: putSet,
        getSet: getSet
    };
});   

I am able to reach selected from my function defined like this:

setDisplay = function($scope, $mdDialog, shareData) {

    console.log(shareData.getSet()); // this is working

    $scope.selected = shareData.getSet();
    $scope.hide = function() {
        $mdDialog.hide();
    };
    $scope.cancel = function() {
        $mdDialog.cancel();
    };
    $scope.answer = function(answer) {
        $mdDialog.hide(answer);
    };
};

My controller is like this:

app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData',
function ($scope, $http, $mdDialog, $mdToast, shareData) {

    console.log(shareData.getSet()); // NOT WORKING

}]); 

回答1:


You had extra $mdToast in your topicController controller's factory function, you need to remove it.

The reason behind it was not working is, currently you had 4 dependency mentioned in array like ['$scope', '$http', '$mdDialog', 'shareData', function & then you are using its instance inside the function next to DI array. Inside that function you had actually 5 dependencies where $mdToast extra. So behind the scene what happening is $scope of function hold an value of '$scope' DI array likewise you go right to left. But when it comes to $mdToast(in controller function) it was holding a value of 'shareData'(of DI array) & then the next parameter shareData get nothing.

app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData', 
      function ($scope, $http, $mdDialog, shareData) { //<--removed $mdToast
    console.log(shareData.getSet());
  }
]);

NOTE: You are using DI inline array annotation, so the sequence in which dependency are injected in array, in same sequence you should inject then in underlying factory function.



来源:https://stackoverflow.com/questions/37968742/angular-not-able-to-access-variables-in-controller-using-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!