使用AngularJS动态(按需)加载工厂

时间:2014-02-11 20:26:52

标签: angularjs angularjs-factory

根据Dan Wahlin关于动态加载控制器和视图http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs.aspx的文章,我编写了一个示例AngularJS应用程序,其中包含一个小修改,如下所示。

虽然Dan例如提前加载数据服务(main.js),但只有当控制器需要它时才会加载工厂:

main.js

require.config({
    baseUrl: '/app'
});



require([
            'app', 
            'services/routeResolver'
            //'services/mathService'
        ],
        function () {
            angular.bootstrap(document, ['myFirstApp'])
});

mathService.js

'use strict';


define(['app'], function (app) {

    var mathService = function () {
        return {
            add: function(n1, n2) {

                if (isNaN(n1) || isNaN(n2)) {
                    return NaN;
                }
                return parseInt(n1) + parseInt(n2);
            }
        }
        };


    app.factory('mathService', mathService);

});

v2Controller.js

'use strict';


define(['app', 'services/mathService'], function (app) {

    var ctrl = function ($scope, mathService) {

        $scope.greeting = 'Hi there from viewtwoland!';

        $scope.n1 = 0;
        $scope.n2 = 0;
        $scope.result = 0;

        $scope.add = function ()
        {
            $scope.result = mathService.add($scope.n1, $scope.n2); 
        }
    };

    app.register.controller('v2Controller', ['$scope', 'mathService', ctrl]);

});

v2.html

<p>
        {{greeting}}
    </p>

    <input type="text" data-ng-model="n1" id="n1" name="n1" data-ng-change="add()" />&nbsp;&nbsp;&nbsp;
    <input type="text" data-ng-model="n2" id="n2" name="n2" data-ng-change="add()" />

    <div>
        The sum of {{n1}} and {{n2}} is: {{result}}
    </div>

然而,这没有按预期工作。以下是我得到的结果:

{{greeting}} 
    [     ] [     ]
The sum of {{n1}} and {{n2}} is: {{result}} 

任何想法。这是否可行。

1 个答案:

答案 0 :(得分:0)

我通过更改控制器解决了这个问题,如下所示:

define(['app', 'services/mathService'], function (app) {

    var ctrl = function ($scope, mathService) {

        $scope.greeting = 'Hi there from viewtwoland!';

        $scope.n1 = 0;
        $scope.n2 = 0;
        $scope.result = 0;

        $scope.add = function ()
        {
            return mathService.add($scope.n1, $scope.n2); 
        }
    };

    app.register.controller('v2Controller', ['$scope', 'mathService', ctrl]);

});

和mathService如下:

'use strict';


define(['app'], function (app) {

    var mathService = function () {
        return {
            add: function(n1, n2) {

                if (isNaN(n1) || isNaN(n2)) {
                    return NaN;
                }
                return parseInt(n1) + parseInt(n2);
            }
        }
        };


    app.register.factory('mathService', mathService);

});

如果你有更好的解决方案来解决这个问题,我会很有兴趣知道它。