AngularJs中的简单工厂调用给出错误

时间:2016-09-26 13:24:17

标签: javascript angularjs factory

在一个简单的例子中,我期待控制台ping我“USA”。相反,我得到一个错误。有人可以帮忙解决吗?

SNIPPET:

<html> 
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
</head> 

<body ng-app="myApp" ng-controller="myCtrl"> 
<script>
//module declaration
var app = angular.module('myApp',[]);
//controller declaration
app.controller('myCtrl',function($scope, myFactory){
    var a = myFactory();
    console.log(a.country);
});

//factory declaration
app.factory('myFactory',function(){
    var obj = {};
    obj.country = "USA";
    return obj;
});
</script> 
</body> 
</html> 

错误:

enter image description here

5 个答案:

答案 0 :(得分:1)

试试这个

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 


<body ng-app="myApp" ng-controller="myCtrl"> 
<script>
//module declaration
var app = angular.module('myApp',[]);
//controller declaration
app.controller('myCtrl',function($scope, myFactory){
    var a = myFactory;
    console.log(a.country);
});

app.factory('myFactory',function(){
    var obj = {};
    obj.country = "USA";
    return obj;
});
</script> 
</body> 

答案 1 :(得分:0)

正如运行时告诉你的那样,myFactory不是一个函数。

var a = myFactory();

此调用无效。你可以这样做。

var a = myFactory;
console.log(a.country);

或者只是:

console.log(myFactory.country);

答案 2 :(得分:0)

    <html> 
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
</head> 

<body ng-app="myApp" ng-controller="myCtrl"> 
<script>
//module declaration
var app = angular.module('myApp',[]);
//controller declaration
//factory declaration
app.factory('myFactory',function(){
    var obj = {};


    return {
        get: function(){
           obj.country = "USA";
            return obj;
        },

    }
});

app.controller('myCtrl',function($scope, myFactory){
    var a = myFactory.get();
    console.log(a.country);
});

</script> 
</body> 
</html> 

答案 3 :(得分:0)

您可以使用select to_date(start_time,'hh24:mi')-to_date(end_time,'hh24:mi') FROM table_name;

的替代方式
$injector

答案 4 :(得分:0)

您收到错误,因为工厂返回一个服务对象,并且您尝试将其作为函数调用。

检查以下代码段。

&#13;
&#13;
angular
  .module('demo', [])
  .controller('DefaultController', DefaultController)
  .factory('demoFactory', demoFactory);

DefaultController.$inject = ['demoFactory'];

function DefaultController(demoFactory) {
  console.log(demoFactory.country);
}

function demoFactory() {
  var service = {
    country: 'USA'
  };
  
  return service;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl"></div>
</div>
&#13;
&#13;
&#13;