2016-10-17 8 views
-1

저는 사용자 정의 지시문을 사용하는 간단한 응용 프로그램을 가지고 있지만 분리 된 스코프를 사용하려고 할 때 완전히 손실되었습니다. 제발 틈새를 채우기 위해 무엇을 써야하는지 알려주세요.AngularJs 지시어는 범위를 분리합니다

앱의 아이디어는 무엇인가요?

a) app 컨트롤러는 $ http를 사용하여 서비스에서 menu_list 항목을 생성 한 다음 found 함수를 사용하여 foundItems 배열을 반환합니다 (모두 완료되었습니다!).
b) 지시문에는 찾은 항목을 던져 순서대로 나열한 목록이 표시되고 필요하면 항목을 제거하기 위해 각 항목 옆에 버튼이 표시됩니다 (여전히 필요함).

내가 뭘 놓친 거지 :

은 내가 < 말을 댓글 내 directive.html 세 곳이 -도>

- == < == < == 무슨 말을 <을 내 index.html을 나는 < 댓글을 달았습니다 - 확실하지 않음 - 확실하지 - -> 뿐만 아니라 내 app.js에서와 < 주석>

이 5 곳에서 모양과 제발 말해 무엇 할 것!

index.html을 :

<!doctype html> 
<html lang="en" ng-app="NarrowItDownApp"> 

<head> 
    <title>Narrow Down Your Menu Choice</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="styles/bootstrap.min.css"> 
    <link rel="stylesheet" href="styles/styles.css"> 
</head> 

<body> 
    <div class="container" ng-controller="NarrowItDownController"> 
     <h1>Narrow Down Your Chinese Menu Choice</h1> 

     <div class="form-group"> 
      <input type="text" placeholder="search term" class="form-control" ng-model="searchTerm"> 
     </div> 
     <div class="form-group narrow-button"> 
      <button class="btn btn-primary" ng-click="found(searchTerm)">Narrow It Down For Me!</button> 
     </div> 
     <found-items items="found(searchTerm)"></found-items> 
     <!-- Not sure --> 
    </div> 

    <script src="scripts/angular.min.js"></script> 
    <script src="scripts/app.js"></script> 
</body> 

</html> 

directive.html :

<div> 
    <ol> 
     <li ng-repeat="item in items"><!-- <== What to say here <== <== --> 
      {{ item.name }}, {{ item.shortName }}, {{item.description}} 
      <button ng-click="remove">Remove item</button> <!-- <== What to say here <== <== --> 
     </li> 
    </ol> 
    <div class="error" ng-if="foundItem.length">nothing found 
    </div> <!-- <== What to say here <== <== --> 
</div> 

app.js :

var app = angular.module('NarrowItDownApp', []); 

app.controller('NarrowItDownController', ['$scope', 'MenuSearchService', function($scope, MenuSearchService) { 
    var $scope = $scope; 
    $scope.searchTerm = 'soup'; 
    $scope.found = function() { 
     return MenuSearchService.getMatchedMenuItems($scope.searchTerm); 
    } 
    console.log(MenuSearchService.getMatchedMenuItems($scope.searchTerm)); 

    $scope.remove = function(index){ 
     service.removeItem(index); 
    } 
}]); 

app.service('MenuSearchService', ['$http', function($http) { 
    var service = this; 
    service.getMatchedMenuItems = function(searchTerm) { 
     searchTerm = searchTerm.toLowerCase(); 
     return $http({ 
       method: 'GET', 
       url: 'https://davids-restaurant.herokuapp.com/menu_items.json' 
      }) 
      .then(function(response) { 
       var result = response.data.menu_items; 
       console.log('Result: ' + result.length); 
       var foundItems = []; 
       result.forEach(function(obj) { 
        if (searchTerm != '') { 
         if ((obj.name.indexOf(searchTerm) != -1) || (obj.description.indexOf(searchTerm) != -1)) { 
          foundItems.push(obj); 
         } 
        } 
       }) 
       console.log('Found Items: ' + foundItems.length) 
       return foundItems; 

      }, function(error) { 
       console.log('Error from $http' + error); 
      }); 
    } 
     service.removeItem = function(index){ 
     service.getMatchedMenuItems(index).splice(index, 1); 
    } 
}]); 

app.directive('foundItems', function() { 
    var ddo = { 
     templateUrl: 'directive.html', 
     scope: { 
      items: '<found' // Not sure 
     } 
    } 
    return ddo; 
}); 

주 : 병 대구 나중에 메소드를 제거하고 질문을 업데이트하십시오. 그러나 지금은 essentail이 아닙니다. 미리 감사드립니다. 업데이트 : 서비스 및 컨트롤러에서 remove 메소드를 코딩했습니다.

+0

정직 할 몇 가지가있다; 서비스는 항목 배열을 반환해야하며 배열은 항목 속성을 통해 지시문에 전달되어야하고 지시문 템플릿은 배열을 반복하고 각 항목을 기반으로 작업을 수행해야합니다. ... jsFiddle을 사용하여 시연하는 것이 더 쉬울 것입니다. –

+0

분리 범위가 있으므로 클릭 이벤트와 같은 기능을 사용하려면 해당 이벤트에 대한 바인딩이 있거나 사용자 지정 지시문의 컨트롤러에서 처리해야합니다. – Zach

+0

@Neil Hibbert 나는 그때 방법으로부터 배열을 이미 반환하고 있다고 믿는다. –

답변

1

지시어와 구성 요소 사이를 오가는 것처럼 보입니다. 구성 요소에는 <을 참조한 단방향 바인딩이 있습니다.ng-repeat을 알 - 다음과 같이

app.controller('NarrowItDownController', ['$scope', 'MenuSearchService', function($scope, MenuSearchService) { 
    $scope.searchTerm = 'soup'; 
    // It looks like you want to use found as both the results and the search function. Separate them. 
    $scope.search = function(searchTerm) { 
     console.log('Searching for ' + searchTerm); 
     MenuSearchService.getMatchedMenuItems(searchTerm).then(function(foundItems) { 
     // The service executes asynchronously so use the then() to create a callback and store the results. 
     $scope.results = foundItems; 
     }); 
    }; 

    $scope.search($scope.searchTerm); 
}]); 

마크 업입니다 : 귀하의 지침은 다음과 같이한다 : 컨트롤러에서 다음

app.directive('foundItems', function() { 
    var ddo = { 
     restrict: 'E', //Since this is a directive and not a component, you need to define which type (E = Element since you're using <found-items>) 
     templateUrl: 'directive.html', 
     scope: { 
      items: '=' // This is two-way binding which you'll need for the array 
     }, 
     controller: function ($scope) { 
     $scope.remove = function (item) { 
      // This can be where you make a call to your service to remove the item on the server 
      var index = $scope.items.indexOf(item); 
      if(index >= 0) { 
      $scope.items.splice(index, 1); 
      } 
     } 
     } 
    } 
    return ddo; 
}); 

을, 당신이 당신의 검색 기능과 결과를 분리하는 것이 좋습니다. 변수를 변수에 할당하고 해당 변수를 요소 내부에서 사용합니다. 그렇다면 ng-if은 결과가 0 일 때 div가 표시되어야하는 조건입니다.

<div> 
    <ol> 
     <li ng-repeat="item in items"> 

      {{ item.name }}, {{ item.shortName }}, {{item.description}} 
      <button ng-click="remove(item)">Remove item</button> 

     </li> 
    </ol> 
    <div class="error" ng-if="items.length == 0">nothing found </div> 

</div> 

http://plnkr.co/edit/VqaYgNx56qbjAQT1Xd3m?p=preview

+0

무슨 전설! 참으로 대단히 감사합니다. –

+0

if 조건이 만족스러운 이유는 무엇입니까? if (index> = 0) { $ scope.items.splice (index, 1); } –

+0

배열에서 항목을 찾기 위해'indexOf'를 할 때, 발견되면 0 이상의 인덱스를 반환합니다. 그렇지 않으면 -1을 반환하므로'if (index! == -1)' – Zach

-1

설명서 here을 확인하십시오. 지시문에서 사용할 바인딩 유형을 정의해야합니다. 객체를 지시문에 전달하면 =이됩니다. 그래서 지침 범위 정의는 다음과 같이 될 것입니다 : 그 후

scope: { 
    items: '=' 
} 

를, 당신의 지시 범위는 items은 모든 다른 부모 범위 객체에 정의 된 것입니다. 그리고 당신은 언제나처럼 그 변수를 사용할 수 있습니다 것들에 대한

ng-repeat="item in items" 

당신이 당신의 지시에 기능을 구현할 수 있습니다 제거 좋아하지만, 무엇을 할 것 것은 현재 질문의 범위를 벗어납니다. 아마 $ http를 부를까요?

+0

초보자로서 나를 생각해 보라. 퍼즐을 완성하고 살아있는 예제를 이해하려고 노력하는 누락 된 조각이 필요하다. –

+0

초급자로서, 적어도 한 번은 전체 문서를 읽어야합니다. 그리고 프레임 워크 작성자가 만든 것과 같은 것을 재현 해보십시오. 예를 들어, 한 줄만 리턴 될 변수에 지시문을 정의합니다. 문서는 항상'return {}'을 보여줍니다. –