0

コントローラとビューの動的ロードに関する 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}} 

何か案は。これはまったく実行可能ですか。

4

1 に答える 1