简体   繁体   English

AngularJS指令从URL获取数据

[英]Angularjs directive get data from url

i define a directive in angularjs that have a url to fetch data from data base. 我在angularjs中定义了一个指令,该指令具有从数据库中获取数据的网址。 i display part of code. 我显示部分代码。 my directive is : 我的指令是:

app.directive('getData', function() {

return {
 restrict: 'E',
  scope: {
    url: '@',
    suggestion: '=data'
   },
  controller: ['$scope','$http', function($scope,$http){
    $http.get($scope.url)
      .success(function (data) {
        console.log(data);// display data 
        $scope.Items = data;
      });
   })
  template:
           <li\
          suggestion\
              ng-repeat="suggestion in suggestions track by $index"\
          </li>\
}

now when i create a directive such as this in html 现在当我在html中创建这样的指令时

<get-data url="/public/getEmployee" data="Items"></get-data>

but no data display in it, while same code in directive controller be in an angularjs controller work correctly. 但其中没有数据显示,而指令控制器中的相同代码在angularjs控制器中正常工作。

You are calling the http request inside the directive and getting the data inside the directive, so you do not need to pass the suggestion variable in scope. 您正在指令内部调用http请求,并在指令内部获取数据,因此您无需在scope中传递suggestion变量。

Directly use Items array in the template item in Items track by $index . item in Items track by $index直接item in Items track by $index中的模板item in Items track by $index使用Items数组。

Isolated scope variable passed in scope property are used to get data from external dependencies. scope属性中传递的隔离范围变量用于从外部依赖项获取数据。

And your directive usage should be 您的指令用法应为

<get-data url="/public/getEmployee"></get-data>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM