将范围传递给 ng-include [英] Angular passing scope to ng-include

查看:22
本文介绍了将范围传递给 ng-include的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,我用 ng-includeng-repeat 在我的应用程序的多个地方使用了它,就像这样:

<divng-repeat="项目中的项目"ng-include="'item.html'"ng-controller="项目控制器"></div>

在控制器/模板中,我希望 item 值存在,整个事情都是围绕这个想法构建的.不过,现在我需要以稍微不同的方式使用控制器,没有 ng-repeat,但仍然需要能够传入 item.我看到 ng-init 并认为它可以做我需要的,就像这样:

<divng-init="item = leftItem"ng-include="'item.html'"ng-controller="项目控制器"></div>

但这似乎不起作用.任何人都知道如何在像这样的单一实例中传入作用域变量?

上面的控制器正在加载 leftItemrightItem 值,如下所示:

.controller('MainController', function($scope, ItemModel) {ItemModel.loadItems().then(功能(项目){$scope.$apply(function() {$scope.leftItem = items.left;$scope.rightItem = items.right;});});});

解决方案

我最终把它改写成一个指令,并用

绑定作用域中所需的值

范围:{项目:'='}

I have a controller that I wrote that I use in multiple places in my app with ng-include and ng-repeat, like this:

<div
  ng-repeat="item in items"
  ng-include="'item.html'"
  ng-controller="ItemController"
></div>

In the controller/template, I expect the item value to exist, and the whole thing is built around this idea. Now, though, I need to use the controller in a slightly different way, without the ng-repeat, but still need to be able to pass in an item. I saw ng-init and thought it could do what I needed, like this:

<div
  ng-init="item = leftItem"
  ng-include="'item.html'"
  ng-controller="ItemController"
></div>
<div
  ng-init="item = rightItem"
  ng-include="'item.html'"
  ng-controller="ItemController"
></div>

But that does not seem to be working. Anyone have any ideas how I can pass in a variable for scope in a singular instance like this?

Edit: The controller above this is loading in the leftItem and rightItem values, something like this:

.controller('MainController', function($scope, ItemModel) {
    ItemModel.loadItems()
        .then(function(items) {
            $scope.$apply(function() {
                $scope.leftItem = items.left;
                $scope.rightItem = items.right;
            });
        });
});

解决方案

I ended up rewriting it into a directive and binding the needed value in the scope with

scope: {
    item: '='
}

这篇关于将范围传递给 ng-include的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆