我的代码有问题。在我的应用程序中,我有2个控制器,一个是加载所有数据,第二个是显示选项卡。
以下是设置:
<div class="row" ng-app="quotation_list">
<div class="col-md-12" ng-controller="quoteList">
<section ng-controller="PanelController as panel">
<div class="panel pane-default" ng-show="panel.isSelected(1)">
...
<div class="row">
<div class="form-group">
<label>VAT(%): </label>
<input type="number" class="form-control text-right" ng-model="vat_rate" />
</div>
</div>
<button class="btn btn-default" type="button" ng-click="computePercentage()">TEST VALUE</button>
</div>
</section>
</div>
</div>
我正在尝试获取模型 vat_rate 的值,但我得到的是未定义的值
这是我的功能:
var quotationList = angular.module('quotation_list', ['jsonFormatter','ui.bootstrap','ckeditor']);
quotationList.controller('quoteList', function($scope, $http) {
//some codes ...
$scope.computePercentage = function() {
console.log($scope.vat_rate);
}
});
我不知道我的错误在哪里。还有一个问题是,如果我在控制器内部创建一个控制器,那很好吗?就像我做的一样?
好的,我希望你能帮助我。 :)
答案 0 :(得分:3)
是的,你可以在控制器内创建一个控制器。
<body ng-controller="firstController">
<span>{{scopeinFirstController}}</span>
<div ng-controller="secondController">
<span>{{scopeinSecondController}}</span>
<div ng-controller="lastController">
<span>{{scopeinlastController}}</span>
</div>
</div>
</body>
答案 1 :(得分:1)
正如我在评论中指出的那样,您在这里混合样式,这使得难以在正确的范围内访问您的属性。此外,由于您的属性是没有先前赋值的原始值,而不是对象,因此会遇到JavaScript Prototype Inheritance个问题。
以下是我建议如何重构外部控制器以使用controller as
,稍微简化控制器,并明确显示属性属于哪个控制器。这有另外的附带好处,即自动执行与原型继承有关的“点规则”。
var quotationList = angular.module('quotation_list',
['jsonFormatter','ui.bootstrap','ckeditor']);
quotationList.controller('quoteListController', function($http) {
var quoteList = this; //store a reference to this for easy use
//some codes ...
quoteList.computePercentage = function() {
console.log(quoteList.vat_rate);
}
});
HTML:
<div class="row" ng-app="quotation_list">
<div class="col-md-12" ng-controller="quoteListController as quoteList">
<section ng-controller="PanelController as panel">
<div class="panel pane-default" ng-show="panel.isSelected(1)">
...
<div class="row">
<div class="form-group">
<label>VAT(%): </label>
<input type="number" class="form-control text-right" ng-model="quoteList.vat_rate" />
</div>
</div>
<button class="btn btn-default" type="button" ng-click="quoteList.computePercentage()">TEST VALUE</button>
</div>
</section>
</div>
</div>