2

I'm pretty new to AngularJS, I want to pass the scope to a service so I can perform a tag search based on the scope.value.

<div data-ng-app="instaSearch" data-ng-controller="search">

  <div>
    <input type="text" value={{value}} data-ng-model='value'/>
  </div>

 <p data-ng-hide="value">type a tag</p>
 <p data-ng-show="value">...looking for {{value}}</p>


<ul>

  <li data-ng-repeat="r in results">
    <a>
      <img ng-src="{{r.images.thumbnail.url}}"  alt="" />
    </a>
  </li>

</ul>  

</div>

Here is the JS

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

app.factory('instagram', function($resource){

    return {
    searchTag: function(callback){

      var api = $resource('https://api.instagram.com/v1/tags/:tag/media/recent?client_id=:client_id&callback=JSON_CALLBACK',{
                client_id: '3e65f044fc3542149bcb9710c7b9dc6c',
        tag:'dog'
            },{
                fetch:{method:'JSONP'}
            });

            api.fetch(function(response){
                callback(response.data);

            });
    }
    }

});

app.controller('search', function($scope, instagram){

  $scope.$watch('value', function(){
    $scope.results = [];

    instagram.searchTag(function(data){
      $scope.results = data;
    });
  });

});

working example

4

1 回答 1

2

您可以使用 访问该值$scope.value

app.factory('instagram', function ($resource) {
    return {
        searchTag: function (tag, callback) {
            var api = $resource('https://api.instagram.com/v1/tags/:tag/media/recent?client_id=:client_id&callback=JSON_CALLBACK', {
                client_id: '3e65f044fc3542149bcb9710c7b9dc6c',
                tag: tag
            }, {
                fetch: {
                    method: 'JSONP'
                }
            });

            api.fetch(function (response) {
                callback(response.data);

            });
        }
    }

});

app.controller('search', function ($scope, instagram) {
    $scope.$watch('value', function () {
        $scope.results = [];
        instagram.searchTag($scope.value, function (data) {
            $scope.results = data;
        });
    });
});

演示:http ://codepen.io/anon/pen/GHbIl

于 2013-09-21T15:27:03.960 回答