Pass scope to Service on AngularJS

只愿长相守 提交于 2019-12-08 02:43:46

问题


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


回答1:


You can access the value using $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;
        });
    });
});

Demo: http://codepen.io/anon/pen/GHbIl



来源:https://stackoverflow.com/questions/18934154/pass-scope-to-service-on-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!