无法在角度服务中访问对象属性

时间:2017-01-13 03:34:47

标签: javascript angularjs service

我尝试使用属性通道设置一个名为channelid的对象。但是,当我尝试访问它时,我返回Object {}

服务

function Service($http){
  var service = this;
  var channelid = {};

  // Set channel ID
  service.SetChannelID = function(id){
    channelid.channel = id;
  };

  // Get Channel Id
  service.GetChannelID = function(){
    return channelid;
  };

控制器

// Set channel id
Service.SetChannelID(channel.id);

// Retrieve channel id
var channelID = Service.GetChannelID();

当我尝试访问它时。

console.log(channelID.channel);

打印未定义的

如果我打印

console.log(channelID);

它打印对象{}

>Object
  channel:"C3NBGTQJD"
  __proto__: Object 

不是对象{channel:" C3NBGTQJD"}

1 个答案:

答案 0 :(得分:0)

供参考,你可以按照这个小提琴

"http://jsfiddle.net/ADukg/9158/"

服务

  myApp.service('myService', function(){
  var channelObj={};
  var service = this;

  service.setChannelId = function(id) {
    channelObj.channel = id;
  };

  service.getChannel = function() {
    return channelObj;
  }

});

控制器

$scope.setChannelId = function (id) {
        myService.setChannelId(id);
}

$scope.getChannelId = function() {
        var channelObj = myService.getChannel()
        alert(channelObj.channel);
}

模板

<div ng-controller="MyCtrl">
  <button ng-click="setChannelId(5)">
    Set Channel
  </button>
  <button ng-click="getChannelId()">
    Get Channel
  </button>

</div>