私は AngularJS を学ぼうとしているので、非常に単純な Angular アプリを作成しています。工場を作成してコントローラーを分割しようとするまで、すべてが機能していました(これが正しい方法だと思います)。現在、メイン/インデックスには空のページのみが表示されていますが、ファクトリが実装される前はフォームが表示されていました。私はそれを理解することはできません!注: Yeoman の Angular セットアップを使用しています。
フォルダ構造:
- コントローラ
- about.js
- conversion.js
- main.js
- app.js
これが私のメイン/インデックス ページ (main.html) です。
<div ng-controller="MainCtrl as measure">
<form role="form">
<h2>BMI udregner:</h2>
<div class="form-group">
<label for="exampleInputEmail1">Vægt</label>
<input type="number" class="form-control" ng-model="measure.weight">
<select ng-model="measure.inMass" class="form-control input-sm" >
<option ng-repeat="m in measure.mases">{{m}}</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Højde</label>
<input type="number" class="form-control" ng-model="measure.height">
</div>
<div>
<b>Total:</b>
<span>
{{ measure.total(measure.inMass) }}
</span>
</div>
</div>
</form>
私のコントローラー(main.js):
'use strict';
/**
* @ngdoc function
* @name measureBmiApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the measureBmiApp
*/
angular.module('measureBmiApp', ['Conversion'])
.controller('MainCtrl', ['weightConverter', function(weightConverter) {
this.height = 180;
this.weight = 90;
this.inMass = 'kg';
this.mases = weightConverter.mases;
this.total = function total(outMass) {
return weightConverter.convertMass(this.weight / (this.height / 100 * this.height / 100), outMass);
};
}]);
そして私の工場(conversion.js):
'use strict';
angular.module('Conversion', [])
.factory('weightConverter', function() {
var mases = ['kg', 'lb'];
var kgToLb = {
kg: 1,
lb: 2.2046226
};
var convertMass = function (amount, outMass) {
return amount * kgToLb[outMass];
};
return {
mases: mases,
convertMass: convertMass
};
});
そして app.js:
'use strict';
/**
* @ngdoc overview
* @name measureBmiApp
* @description
* # measureBmiApp
*
* Main module of the application.
*/
angular
.module('measureBmiApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/'
});
});