2015-02-11 18 views
1

我想實現以下目的:如何創建一個可以發出ajax請求的angularjs指令?

<users name="allUsers" get-all></users> 

,然後呈現一個選擇元素與所有用戶的列表。這是我到現在爲止所做的:

var app = angular.module("Security", []); 

app.directive("users", function() { 
    return { 
     restrict: 'E' 
    }; 
}); 

app.directive("getAll", function() { 
    return { 
     restrict: 'A' 
    }; 
}); 

大量的谷歌搜索後,我沒有發現任何相關信息。可能我正在尋找老鼠而不是狗...

編輯: 好了,現在我有一個服務,但仍然不知道如何使用範圍連接。

app.factory('userService', function ($http) { 
    return { 
     getAll: function() { 
      return $http.get('/users/getAll') 
         .then(function (result) { 
          return result.data; 
          // [{Id: 1, Name: 'John'}, {Id: 2, Name: 'Mark'}] 
         }); 
     } 
    } 
}); 

app.directive("getAll", function() { 
    return { 
     restrict: 'A', 
     require: '^users', 
     template: '<option value="{{Id}}">{{Name}}</option>', 
     link: function (scope, element, attrs, userCtrl) { 
      userService.getAll() 
         .then(function (result) { 
          // What should I do? 
         }); 
     } 
    }; 
}); 
+3

好,通常你會使用一個服務來發送Ajax請求,然後進行指令依賴於它。然而,我不確定在指令中發送ajax請求的想法有多好,這是由於在摘要循環中請求發送了多少次。工作錯誤的工具(這將解釋缺乏搜索結果)。 – 2015-02-11 16:35:15

+0

謝謝您的評論。我真正想要實現的是對這個「組件」的簡單重用,因爲這經常被使用。任何其他想法? – 2015-02-11 16:45:52

+1

您可以將它視爲一個視圖,並給出它自己的控制器/模板,您可以重複使用多個路由。 – 2015-02-11 16:46:39

回答

4

我明白了。

var userModule = angular.module("Users", []); 

userModule.factory('userService', ['$http', function ($http) { 
    return { 
     getAll: function() { 
      return $http.get('/security/users/getAll') 
         .then(function (result) { 
          return result; 
         }); 
     } 
    } 
}]); 

userModule.directive("users", function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     template: '<select><option ng-repeat="item in collection" value="{{item.Id}}">{{item.Name}}</option></select>', 
     scope: true 
    }; 
}); 

userModule.directive("getAll", ['userService', function (service) { 
    return { 
     restrict: 'A', 
     scope: true, 
     link: function (scope) { 
      service.getAll() 
        .then(function (result) { 
         scope.collection = result.data; 
        }); 
     } 
    }; 
}]); 

而且你可以使用它像這樣:

<users get-all></users>