按照 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'])
});
数学服务.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()" />
<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}}
有任何想法吗。这是否可行。