>  기사  >  웹 프론트엔드  >  AngularJS Phonecat 예제 설명

AngularJS Phonecat 예제 설명

高洛峰
高洛峰원래의
2016-12-06 13:09:311014검색

머리말

최근에 AngularJS에 대한 정보를 읽었는데, 공식 홈페이지에 아주 좋은 Phonecat의 예가 있어서 한동안 보고 나니 참을 수 없었습니다. 단순히 제가 직접 구현해 본 것인데, 질문이 있을 때 그 안에서 답을 찾는 것도 좋은 방법입니다. 아무리 말하거나 보아도 스스로하는 것이 더 좋으므로 시작합시다.

텍스트

1. 레이아웃

홈페이지의 사이드바는 입력박스와 드롭다운박스로 이루어져 있으며, 오른쪽은 목록 수정시 홈페이지는 확대되지 않습니다. 세부정보 페이지를 일부 변경하고 단순화한 후 사용자 정의 명령(캐러셀 이미지) 추가를 고려해보세요.

2. 아키텍처 분석

먼저 사용해야 할 서비스를 생각해 보세요.
우리가 할 일은 단일 페이지 애플리케이션이므로 $route 및 $location을 제공해야 합니다. 리소스를 얻으려면 $resource 서비스를 사용하세요. 홈페이지 데이터를 필터링하고 정렬하려면 $filter 서비스를 사용하세요. 요약하자면:

1) $route 및 $location 서비스는 라우팅 관리 및 점프를 담당합니다.
2) 서비스 $resource는 자원 획득을 담당합니다.
3) $filter 서비스는 데이터 필터링 및 정렬을 담당합니다.

3. 홈페이지 및 상세페이지 보기

1. 홈페이지 보기

<div class="main">
  <div class="side">
    <p>
      <label>Search:</label>
      <input ng-model="filterKey" type="text" style="width:150px; ">
    </p>
    <p>
      <label>Sort by:</label>
      <select ng-model="sortKey">
        <option value="price">price</option>
        <option value="name" ng-selected="true">name</option>
      </select>
    </p>
  </div>
  <div class="content">
    <ul>
      <li ng-repeat="item in data" ng-click="$location.path(&#39;detail/&#39;+item.id)">
        <img ng-src={{item.img}}>
        <div>
          <h2>名字:{{item.name}}</h2>
          <p>性能:{{item.title}}</p>
          <p>价格:{{item.price | currency}}</p>         
        </div>
      </li>
    </ul>
  </div>
</div>

2. 상세페이지 보기

<slide></slide>是一个自定义指令,实现轮播图的功能
 
<div class="detail">
  <slide links=&#39;links&#39; w=&#39;200&#39; h=&#39;200&#39;></slide>
  <div class="text">
    <h2>设备:{{data.name}}</h2>
    <p>性能:{{data.desc}}</p>
  </div>
</div>

4. 논리 분석

1. 먼저 외부 리소스 infor.json의 정보를 설명합니다. 배열이며 배열의 각 항목은 다음 필드를 포함하는 json 객체입니다.

{
    "id" : 1,
    "name" : "aaa",
    "title" : "bbb",
    "desc" : "ccc",
    "img" : "img/a.jpg",
    "price" : 100,
    "showList" : "[{"url":"img/b.jpg"},{"url":"img/c.jpg"}]"
}

2. 경로 관리($route)

m1.config([&#39;$routeProvider&#39;,function($routeProvider){
 
  $routeProvider
    .when(&#39;/index&#39;,{
      templateUrl : &#39;template/index.html&#39;,
      controller : &#39;index&#39;
    })
    .when(&#39;/detail/:str&#39;,{
      templateUrl : &#39;template/detail.html&#39;,
      controller : &#39;detail&#39; 
    })
    .otherwise({
      redirectTo : &#39;/index&#39;
    });
 
}]);

모양이 다음과 같은 경우 http:// localhost/phonecat/phone.html#/index 는 인덱스 템플릿을 로드합니다

모양이 http://localhost/phonecat/phone.html#/detail/0 이면 세부 템플릿을 로드합니다

기본값은 http://localhost/phonecat/phone.html#/index

3. 홈페이지(색인) 논리적 분석

홈페이지 리소스 로딩:

var arr = [];
var objRe = $resource(&#39;infor.json&#39;); 
$scope.data = arr = objRe.query(); //获得data数据后首页即可进行渲染

홈페이지 데이터 필터링 및 정렬:

  $scope.$watch(&#39;filterKey&#39;,function(){ //监听输入框的数据变化,完成数据的筛选
    if($scope.filterKey){
      $scope.data = $filter(&#39;filter&#39;)(arr,$scope.filterKey);
    }else{
      $scope.data = arr;
    } 
  })
 
  $scope.$watch(&#39;sortKey&#39;,function(){  //监听select下拉框的数据变化,完成数据的排序
    if($scope.sortKey){
      $scope.data = $filter(&#39;orderBy&#39;)($scope.data,$scope.sortKey);
    }else{
      $scope.data = arr;
    }
  })
 
 
//这里有个需要注意的地方,我们用一个数组arr作为媒介,避免bug

목록을 클릭하여 세부정보 페이지로 이동하세요:

$scope.$location = $location; //将$location挂载到$scope下,模板中便可使用$location提供的方法

템플릿은 다음과 같습니다:

<li ng-repeat="item in data" ng-click="$location.path(&#39;detail/&#39;+item.id)">  --点击的时候将列表跳转到详情页

4. 상세페이지 논리적 분석

m1.controller(&#39;detail&#39;,[&#39;$scope&#39;,&#39;$resource&#39;,&#39;$location&#39;,function($scope,$resource,$location){
  var id = parseInt($location.path().substring(8));  //获取索引
  $resource(&#39;infor.json&#39;).query(function(data){
    $scope.data = data[id];
    $scope.links = eval($scope.data.showList);  //自定义指令需要用到此数据
  });
 
}]);
 
//注意:$resource.query()为异步操作。数据相关的逻辑需要在回调中完成,否则可能会出现数据undefined的情况。

5. 맞춤 지정 슬라이드 작성

AngularJS는 매우 강력하며 구성 요소 기반 개발을 위한 솔루션을 제공합니다. 간단히 캐러셀 컴포넌트를 구현해 보겠습니다.

사용예: 7ad2aba9282b899f33789a9017ea8b86813d8b7ad24b2efd298fbc1d2e96befb

템플릿(slide.html)은 다음과 같습니다. :

<div class="slide">
 <ul>
   <li ng-repeat="item in links">
     <img ng-src={{item.url}}>
   </li>
 </ul>
</div>

m1.directive(&#39;slide&#39;,function(){
  return {
    restrict : &#39;E&#39;,
    templateUrl : &#39;template/slide.html&#39;,
    replace : true,
    scope : {
      links : &#39;=&#39;,
      w : &#39;@&#39;,
      h : &#39;@&#39;
    },
    link : function(scope,element,attris){
      setTimeout(function(){
        var w = scope.links.length * scope.w;
        var h = scope.h;
        var iNow = 0;
 
        $(element).css({&#39;width&#39;:scope.w,&#39;height&#39;:h,&#39;position&#39;:&#39;relative&#39;,&#39;overflow&#39;:&#39;hidden&#39;})
        $(element).find(&#39;ul&#39;).css({&#39;width&#39;:w,&#39;height&#39;:h,&#39;position&#39;:&#39;absolute&#39;});
        setTimeout(function(){
          $(element).find(&#39;li&#39;).css({&#39;width&#39;:scope.w,&#39;height&#39;:h,&#39;float&#39;:&#39;left&#39;});
          $(element).find(&#39;img&#39;).css({&#39;width&#39;:scope.w,&#39;height&#39;:h});      
        },0);
 
        setInterval(function(){
          iNow++;
          $(element).find(&#39;ul&#39;).animate({&#39;left&#39;:-iNow*scope.w},function(){
            if(iNow==scope.links.length-1){
              $(element).find(&#39;ul&#39;).css(&#39;left&#39;,0);
              iNow = 0; 
            } 
          });
        },1000)      
      },50)
 
    }
  } 
})

결론

AngularJS는 라우팅 관리와 같은 유용한 기능을 많이 제공합니다. , 데이터 필터링 등 더 강력한 기능을 사용하려면 추가 조사가 필요하며 이 기사는 좋은 시작일 뿐입니다.


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.