gpt4 book ai didi

javascript - AngularJS 不适用于多个 Controller

转载 作者:行者123 更新时间:2023-11-28 13:18:22 25 4
gpt4 key购买 nike

我是 AngularJS 新手,不幸的是我的代码无法工作。我想要三个下拉字段,但我只能做一个。如果我使用如下所示的代码,则只有第一个下拉菜单有效;第二个和第三个是空的。

我担心这是因为我不知道AngularJS,或者我忘记了......

我已经用谷歌搜索了这个东西,但我没有找到任何可以帮助我的东西。我尝试了很多不同的方法,但没有任何效果。

这是 html:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

//products
<div ng-app="product-selection" ng-controller="product-controller">
<select ng-model="choosenProduct" ng-options="x for x in products"></select>
<div ng-bind = "choosenProduct"></div>
</div>

//formats
<div ng-app="format-selection" ng-controller="format-controller">
<select ng-model="choosenFormat" ng-options="x for x in formats"></select>
</div>

//weights
<div ng-app="weight-selection" ng-controller="weight-controller">
<select ng-model="choosenWeight" ng-options="x for x in weights"></select>
</div>
</body>
</html>

这是 JS:

<script>
var product = angular.module('product-selection',[]);
var weight = angular.module('weight-selection',[]);
var format = angular.module('format-selection',[]);

//products
product.controller('product-controller', function($scope){
$scope.products = ["Brief", "Postkarte", "Infopost", "Büchersendung", "Warensendung", "PZA" ,"Päckchen", "Blindensendung"];
});

//formats
format.controller('format-controller', function($scope){
$scope.formats = ["Standard", "Kompakt", "Groß", "Maxi", "Maxi bis 2kg"];
});

//weights
weight.controller('weight-controller', function($scope){
$scope.weights = ["0-50g", "51-100g", "101-200g", "201-300g"];
});
</script>

最佳答案

Angularjs只会引导第一次出现的ng-app,您可以手动引导其他两个,但多个应用程序很可能会给您带来很多问题,特别是在 Controller 和应用程序之间共享数据时可能是重复代码的来源(格式化程序,一些小的公共(public)部分),如果您想按模块分离某些逻辑,您可以这样做并将所有特定模块注入(inject)一个模块,即

var app = angular.module('app',['product-selection', 'weight-selection', 'format-selection']);
var product = angular.module('product-selection',[]);
var weight = angular.module('weight-selection',[]);
var format = angular.module('format-selection',[]);

//products
product.controller('product-controller', function($scope){
$scope.products = ["Brief", "Postkarte", "Infopost", "Büchersendung", "Warensendung", "PZA" ,"Päckchen", "Blindensendung"];
});

//formats
format.controller('format-controller', function($scope){
console.log('format')
$scope.formats = ["Standard", "Kompakt", "Groß", "Maxi", "Maxi bis 2kg"];
});

//weights
weight.controller('weight-controller', function($scope){
console.log('weight')
$scope.weights = ["0-50g", "51-100g", "101-200g", "201-300g"];
});

工作中的笨蛋 http://plnkr.co/edit/Rovgs3Ets6oNtrFlu9hi?p=preview

关于javascript - AngularJS 不适用于多个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35656252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com