-1

我有一个项目列表,当用户单击其中一个时,我希望该菜单项的详细信息(项目的类或项目的文本本身 - 即$market变量)使用详细信息(var)发出服务器请求,$market然后填充下面的 div 带有从服务器返回的值(取决于发送的详细信息)。

这是我的代码的样子

    <div ng-controller="MarketCtrl">

        Please select a market:

        <?php foreach ($markets as $market): ?>
            <span class="<?= strtolower(str_replace(' ', '_', $market)) ?>"><?= $market ?></span>
        <?php endforeach; ?>

        You have selected _______ as the market.

        <div>
            <!-- Load items based on the item selected above -->
        </div>

    </div>

我想用 AngularJS 来完成这一切,我已经习惯了 jQuery,但我真的很想用 AngularJS 来完成这一切。

我该怎么办?我应该制定一个新指令,然后将上述元素绑定到指令或其他东西吗?我现在对 AngularJS 有点迷失,我正在浏览 egghead.io 视频,但还没有看到这样的东西。

谢谢。

4

1 回答 1

1

这有点开放式,有很多不同的解决方法。如果市场列表和相应的详细信息很少,我会在一个初始 json 请求中将其全部提取出来,并让我的模型如下所示:

 var markets = [{"name":"market1", "detail": {"description":"blah blah"} }]

html:

<div ng-controller="MarketCtrl">
    Please select a market:
        <span ng-repeat="market in markets" ng-click="setMarket(market)" ng-class="getClass(market.name)">{{market.name}}</span>

         You have selected {{curMarket.name}}as the market.
    <div>
         {{curMarket.detail.description}}
    </div>
</div>

控制器:

MarketCtrl= function($scope){
    $scope.curMarket={};
    $scope.getClass = function(name){
        return name.replace(" ", "_")
    }

    $scope.setMarket(market){
         $scope.curMarket=market;
    }

}

如果你想调用数据导致它太多:

var markets = [{"name":"market1", "id":1 }, {"name":"market2", "id":2}]

html:

<div ng-controller="MarketCtrl">
    Please select a market:
        <span ng-repeat="market in markets" ng-click="getMarket(market)" ng-class="getClass(market.name)">{{market.name}}</span>

         You have selected {{curMarket.name}}as the market.
    <div>
         {{curMarket.detail.description}}
    </div>
</div>

控制器:

MarketCtrl= function($scope, $http){
    $scope.curMarket={};
    $scope.getClass = function(name){
        return name.replace(" ", "_")
    }

    $scope.getMarket(market){
         var url='';
         $http.get(url).success(function(data){
                $scope.curMarket=data;
         });
    }

}
于 2013-09-12T15:43:36.163 回答