How do I create a controller that passes a paramet

2019-09-06 02:38发布

问题:

myApp.controller('consumeProduct', function($scope, $http, $log) {    
        $http({
            method: 'GET',
            url: 'http://localhost:8080/Products'
        }).then(function(response) {  
            $scope.products = response.data;
            $log.info(response);
        });
    });

I have a controller above that consumes and returns all products from my rest api. Now I would like to create another controller that takes a parameter(a string) and try to use this parameter and consume this web service('http://localhost:8080/Products/ProductName/parameter'. Based on what the parameter is, the service should return a specific product. How would I be able to do this? I'm trying to create a services javascript file to consume all of my rest api resources. Thanks.

回答1:

As suggested by sabithpocker, Controllers should only be used to update your view. You may want to use a Service or a Factory for your $http requests. Below is an example of a possible implementation:

myApp.factory('ProductFactory', function($http, $log) {

    var ProductFactory = {};

    ProductFactory.getProduct = function(productName) {
        return $http({
                method: 'GET',
                url: 'http://localhost:8080/Products/ProductName/' + productName
            })
            .then(function(response) {
                return response.data;
            })
            .catch($log.err);
    }

    return ProductFactory;
});

Now you need to inject the above factory into your Controller:

myApp.controller('ProductCtrl', function($scope, $log, ProductFactory) {
    ProductFactory.getProduct('apple')
        .then(function(returnedProduct) {
            $scope.product = returnedProduct;
        })
        .catch($log.err);
});

If you use a Factory or Service for your $http processes, then you may reuse them at will whenever needed (and for other Controllers as well).

For example you may have another view where you want to obtain product information just when clicking on a button. So reusing your Factory you may have a second controller as follows:

myApp.controller('ProductListCtrl', function($scope, $log, ProductFactory) {
    $scope.productClick = function(productName) {
        ProductFactory.getProduct(productName)
            .then(function(returnedProduct) {
                $scope.product = returnedProduct;
            })
            .catch($log.err);
    }
})

And in your html:

<td><button ng-click="productClick(product.name)">Show product</button></td>

I hope this helps.