angularjs值vs工厂

时间:2013-04-15 23:07:00

标签: angularjs

我是angularjs的新手。我试图找出何时使用价值与工厂作为服务。这是我在egghead.io教程中的简单代码:

.value('Data', function(){
    return {message:"I am data from a service"};
  })

Data.message绑定到输入字段。当我启动页面时,输入字段中没有任何内容。如果我将值更改为factory,则默认消息将显示在输入字段中。

以下是控制器:

controller('FirstCtrl', ['$scope','Data',function($scope, Data) {
    $scope.data = Data;
    console.log('exiting first controller');
  }])

和索引文件:

<div ng-controller="FirstCtrl">
   <input type="text" ng-model="data.message">
   <h1>{{data.message}}</h1>
</div>

使用值时,为什么页面空白?我的假设是,应用程序启动时不计算或计算值,而工厂是?

另外,我在哪里可以找到有关$ offer的文档?谢谢大家。

2 个答案:

答案 0 :(得分:19)

将值设置为对象,而不是函数:

app.value('Data', {message:"I am data from a service"});

Plunker

另请参阅provide.value()和此video about $provide(值,常量,服务,工厂,装饰器,提供商)

答案 1 :(得分:-1)

您应该将控制器声明为

   app.controller('DataController', ['Data', function DataController(Data){
      this.data = Data;
   }]);

然后在您的页面中使用它,就像在我的代码中一样

<div ng-controller='DataController as dataController'>
      {{dataController.data()}}
   </div>