我无法在Paragraph代码中显示$ scope数据

时间:2013-09-29 13:24:51

标签: angularjs

我的代码中哪一部分错了? 如果它有很多错误请不要给我UNLIKE:我是如此新的Angularjs

<script>
demoapp = angular.module('demoapp', []);
demoapp.factory('simplefactory', function ($scope) {
    //var customers = [{ name: 'Alireza', family: 'massali' }, { name: 'Ehsan', family: 'abdolahi' }, { name: 'Ali', family: 'Shirvanian'}];
    var customers ="3576324";
    //var factory = {};
    this.GetCust = function () {
       return customers;
    };


    this.PostCust = function (customer) {
        return customers;
    };
    return factory;
});



var xxx = angular.module('mmodule', []);
var conts = {}
conts.simple = function ($scope, simplefactory) {
    $scope.name = simplefactory.GetCust();
}

conts.simple1 = function ($scope) {
    $scope.name1 = "2222";
}

xxx.controller(conts);

这是HTML

<div ng-app='mmodule'>
<p ng-controller='simple'>{{name}}</p></div>

3 个答案:

答案 0 :(得分:1)

您的代码不正确。在您的工厂中,您将返回factory,这是未定义的。如果您想使用GetCust和其他功能,则必须返回this

答案 1 :(得分:1)

我可以尝试让你开始正确的路线。 您似乎使用了2个模块,我认为您有一些理由这样做。 'mmodule'模块正在尝试使用'demoapp'模块中定义的工厂。但它不知道它在哪里。所以你需要做的第一件事就是将'demoapp'模块注入'mmodule'。 所以你需要改变行var xxx = angular.module ....到

var xxx=angular.module('mmodule', ['demoapp']);

现在工厂中定义的功能应该可用。

您建立工厂的方式与我设置工厂的方式不同。我会用:

 demoapp.factory('simplefactory', function () {

   var customers ="3576324";
   //var factory = {};
    return{
     GetCust: function () {
       return customers;
     },


     PostCust: function (customer) {
       return customers;
     }
  };
});

这里有一个吸烟者:http://plnkr.co/edit/WisW6f?p=preview

答案 2 :(得分:1)

您需要的是:

demoapp = angular.module('demoapp', []);
demoapp.factory('simplefactory', function () {

工厂不接受范围

    var customers = "3576324";

    return {
        GetCust: function () {
            return customers;
        },


        PostCust: function (customer) {
            return customers;
        }
    }

您需要返回包含函数的对象

});



var xxx = angular.module('mmodule', ['demoapp']);

最重要的是在这个中注入demoapp模块...

var conts = {}
conts.simple = function ($scope, simplefactory) {
    $scope.name = simplefactory.GetCust();
}

conts.simple1 = function ($scope) {
    $scope.name1 = "2222";
}

xxx.controller(conts);