Angularjs - 根据文本框的值过滤rest api的结果

时间:2014-06-14 18:28:14

标签: angularjs angularjs-directive angularjs-scope

好的 - 所以我有以下服务:

angular.module('myApp.services', ['ngResource'])
     .factory('STLineup', function($resource){
        return $resource('http://someapi.com?filters=location.eventInstance.slug:Slug,artists.tags:ArtistTags,location.name:LocationName', 
            {Slug: '@Slug', ArtistTags: '@ArtistTags', LocationName: '@LocationName'})
      });

以下控制器:

angular.module('myApp.controllers', [])
  .controller('MyCtrl1', ['$scope', 'STLineup', function($scope, stl) {

    $scope.items = {};

    stl.get({'Slug': ':xxxxx-2014', 'ArtistTags': ':electronic|grime', 'LocationName': ':Snakepit'},function(response) {
        $scope.items = response.results;
    });

    $scope.changeCallback = function() {
        stl.get({'Slug': ':xxxxxx-2014', 'ArtistTags': ':electronic|grime'},function(response) {
        $scope.items = response.results;
    });
   }
}]);

以下指令:

angular.module('myApp.directives', [])
    .directive('appLineup', [function() {
        return {
            restrict: 'AEC',
            scope: {
              items: '=',
                  change: '&changeCallback'
            },
            link: function(scope, elem, attrs){

            },
            templateUrl: 'templates/lineup.html'
      };
    }]);

以下模板:

<input type="text" ng-model="LocationName" ng-change="change()" />
<br/>
<div class="item" ng-repeat="item in items">
    <p class="title">{{item.name}}</p> 
</div>

使用以下内容将其添加到UI:

<app-lineup items="items" change-callback="change()" />

呼!!

所以 - 正在加载初始数据,但change事件永远不会被解雇?我在这里做错了什么?!

以下是app.js中的代码;

angular.module('myApp', [
  'ngRoute',
  'ngResource',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',
  'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
  $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

2 个答案:

答案 0 :(得分:0)

scope.change = function() {

忘记你的$,这反过来又不允许模板中的change()做任何事情。

scope.items = response.results;

忘记你的$。

答案 1 :(得分:0)

change()函数在你的控制器范围内声明,但由于你的指令使用了一个隔离范围(即一个没有原型继承自其父节点的范围),它对它一无所知。
您可以将它传递给指令的范围,如下所示:

<!-- The VIEW -->
<app-lineup items="items" change-callback="change()" />

/* The DIRECTIVE */
...
scope: {
    ...
    change: '&changeCallback'
}