【问题标题】:AngularJS: output array (with keys) from php in ng-repeat?AngularJS:ng-repeat中的php输出数组(带键)?
【发布时间】:2013-11-30 17:03:43
【问题描述】:

我有一个 rootScope 变量,它将包含产品的类别,每个类别可能有也可能没有子级。这就是我分配rootScope的方式:

$rootScope.categoryList = $http.get('category').then((result) -> result.data) 

这将请求(向 Laravel 路由)获取类别数据数组,数据的设计如下所示:

$data = array(
        {category: Category, children: array('child1, child2, child3')},
        {category: Category2, children: null},
        {category: Category3, children: array('anotherchild1, anotherchild2')}
    );

而我生成数组的方式是这样的:

public static function GetCategoryListings($ignore=false) {
    $results = DB::table('category')->where('parent','-')->get();
    $data = array();

    if(!is_null($results)) {
        $i = 0;
        foreach($results as $result) {
            $data[$i]['category'] = $result;
            $child_result = DB::table('category')->where('parent',$result)->get();

            if(!is_null($child_result)) {
                foreach($child_result as $child) {
                    $data[$i]['children'][] = $child;
                }
            }
            else
                $data[$i]['children'] = null;

            $i++;
        }
    }
    return $data;
}

现在,我想将我的输出打印到 Angular 的视图中,我该怎么做?我做了 像这样:

<li ng-repeat="cat in categoryList">
                {{cat.category}}
            </li>

但它不起作用,而且我无法输出孩子。有没有办法解决这个问题?

编辑

通过在我看来改成这样的方式解决了我的问题:

<ul>
            <li ng-repeat="cat in categoryList">
                {{cat.category}}
                <ul ng-if="cat.children != null">
                    <li ng-repeat="ch in cat.children">{{ch}}</li>
                </ul>
            </li>
        </ul>

【问题讨论】:

    标签: javascript php arrays angularjs


    【解决方案1】:

    这里可能存在很多不同的问题,但这很可能是它。

    Angular 1.2 no longer automatically unwraps promises in the templates。您必须将语法更改为以下内容:

    $http.get('category').then((result) -> $rootScope.categoryList = result.data)
    

    请记住,如果您依赖 categoryList 作为承诺,这可能会破坏您应用中的其他一些内容。

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 2019-01-27
      相关资源
      最近更新 更多