我正在读一本关于 AngularJS 的书,有些东西让我感到困惑
有两个 Controller
编辑Ctrl
app.controller('EditCtrl', ['$scope', '$location', 'recipe',
function($scope, $location, recipe){
$scope.recipe = recipe;
$scope.save = function(){
$scope.recipe.$save(function(recipe){
$location.path('/view/', + recipe.id);
});
};
$scope.remove = function(){
delete $scope.recipe;
$location.path("/");
};
}]);
成分Ctrl
app.controller('IngredientsCtrl', ['$scope',
function($scope){
$scope.addIngredients = function(){
var ingredients = $scope.recipe.ingredients;
ingredients[ingredients.length] = {};
};
$scope.removeIngredient = function(index) {
$scope.recipe.ingredients.slice(index, 1);
};
}]);
我不明白的是,IngredientsCtrl
为何是 EditCtrl
的子级。我看不出其中的关系。这本书清楚地说明了这种情况,我确信情况确实如此,因为示例应用程序运行良好,但我需要帮助理解是什么使 IngredientsCtrl
成为 EditCtrl
的子级>。对我来说没有意义。
编辑:使用相关 HTML
<div class="control-group">
<label class="control-label" for="ingredients">Ingredients:</label>
<div class="controls">
<ul id="ingredients" class="unstyled" ng-controller="IngredientsCtrl">
<li ng-repeat="ingredient in recipe.ingredients">
<input ng-model="ingredient.amount" class="input-mini">
<input ng-model="ingredient.amountUnits" class="input-small">
<input ng-model="ingredient.ingredientName">
<button type="button" class="btn btn-mini" ng-click="removeIngredient($index)"><i class="icon-minus-sign"></i> Delete </button>
</li>
<button type="button" class="btn btn-mini" ng-click="addIngredient()"><i class="icon-plus-sign"></i> Add </button>
</ul>
</div>
编辑:书中摘录
到目前为止我们看到的所有其他 Controller 都链接到 UI 上的特定 View 。但 配料 Controller 很特别。它是一个在编辑页面上使用的子 Controller 封装高层不需要的某些功能。值得注意的是,由于它是子 Controller ,因此它继承了父 Controller 的范围 Controller (在本例中为编辑/新建 Controller )。因此,它可以访问 来自父级的 $scope.recipe。
编辑:使用路由
var app = angular.module('guthub',
['guthub.directives', 'guthub.services']);
app.config(['$routeProvider',
function($routeProvider){
$routeProvider.
when('/', {
controller: 'ListCtrl',
resolve: {
recipes: function(MultipleRecipeLoader){
return MultipleRecipeLoader();
}
},
templateUrl: '/view/list.html'
}).
when('/edit/:recipeId', {
controller: 'EditCtrl',
resolve: {
recipe: function(RecipeLoader) {
return RecipeLoader();
}
},
templateUrl: '/view/recipeForm.html'
}).
when('/view/:recipeId', {
controller: 'ViewCtrl',
resolve: {
recipe: function(RecipeLoader) {
return RecipeLoader();
}
},
templateUrl: '/view/viewRecipe.html'
}).
when('/new', {
controller: 'NewCtrl',
templateUrl: '/view/recipeForm.html'
}).
otherwise({redirectTo: '/'});
}]);
最佳答案
如果将 ng-controller
指令放置在两个嵌套的 html 元素上,则两个 Controller 共享父子关系。
如果您查看 HTML 模板,您应该会看到如下内容:
<!-- parent controller -->
<div ng-controller="EditCtrl">
<!-- child controller -->
<div ng-controller="IngredientsCtrl"></div>
</div>
关于javascript - 这两个 Controller 有何关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19677865/