工厂没有为控制器提供适当的值

时间:2015-10-29 09:09:44

标签: angularjs angularjs-factory

在我的角度js项目中,工厂没有根据需要向控制器提供值。我总是在视野中得到空洞的结果。当我使用console.log()登录浏览器时,我在控制台中看到的是: [object Object],[object Object],[object Object]。我被困在这里。尝试过很多事情但没有任何效果。

这是我的控制器代码:

var controllers = {};

controllers.ProductController = function ($scope, $route, $routeParams, $location, ProductFactory) {
    $scope.products = [];
    var init = function () {
        $scope.products = ProductFactory.getProducts();
        console.log('got products in controller');
        console.log($scope.products)
    };
    var initProductEdit = function () {
        var code = $routeParams.code;
        if (code = undefined) {
            $scope.currentProduct = {};
        }
        else
        {
            $scope.currentProduct = ProductFactory.loadProductByCode(code);
        }
    };
    $scope.$on('$viewContentLoaded', function () {
        var templateUrl = $route.current.templateUrl;
        if (templateUrl == '/Partials/ProductEdit.html') {
            initProductEdit();
        }
        else if (templateUrl == '/Partials/ProductList.html')
        {
            var code = $routeParams.code;
            if(code!=undefined)
            {
                $scope.deleteProduct(code);
            }
        }
    });
    init();
    $scope.saveProduct = function () {
        ProductFactory.saveProduct($scope.currentProduct);
        $location.search('code', null);
        $location.path('/');
    };
    $scope.deleteProduct = function (code) {
        ProductFactory.deleteProduct(code);
        $location.search('code', null);
        $location.path('/');
    };
};

angSPA.controller(controllers);

这是我的工厂代码:

angSPA.factory('ProductFactory', function () {
    var products = [
        { code: 1, name: 'Game of Thrones', description: 'Series' }
        { code: 2, name: 'DmC', description: 'Game' },
        { code: 3, name: 'Matrix', description: 'Movie' },
        { code: 4, name: 'Linkin Park', description: 'Music Band' }];

    var factory = {};
    console.log('initializing factory');
    factory.getProducts = function () {
        console.log('factory now providing products');
        return products;
    };

    factory.loadProductByCode = function (code) {
        var product;
        for (var i = 0; i < products.length; i++) {
            if (products[i].code == code) {
                product = products[i];
                return product;
            }
        }
    };

    factory.saveProduct = function (product) {
        products.push(product);
        console.log('factory saved product');
    };

    factory.deleteProduct = function (code) {
        var product = factory.loadProductByCode(code);
        if (product != null) {
            products.remove(product);
            console.log('factory deleted product');
        }
    };
    console.log('returning factory');
    return factory;
});

这是我的观点:

<div class="container">
    <h2 class="page-title">Product Listing</h2>
    <div class="searchbar">
        <ul class="entity-tabular-fields">
            <li>
                <label>Search: </label>
                <span class="field-control">
                    <input type="text" data-ng-model="filter.productName" />
                </span>
                <label></label>
            </li>
        </ul>
    </div>
    <h2><a href="#/ProductEdit">Add New Product</a></h2>
    <table class="items-listing">
        <thead>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td data-ng-repeat="product in products|filter:filter.productName"></td>
                <td><a href="#/ProductEdit?code={{product.code}}">{{product.code}}</a></td>
                <td>{{product.name}}</td>
                <td>{{product.description}}</td>
                <td><a href="#/?code={{product.code}}">Delete</a></td>
            </tr>
        </tbody>
    </table>
</div>

我的路由功能:

angSPA.config(function ($routeProvider) {
    $routeProvider
    .when(
    '/',
    {
        controller: 'ProductController',
        templateUrl: 'Partials/ProductList.html'
    })
    .when(
    '/ProductEdit',
    {
        controller: 'ProductController',
        templateUrl: 'Partials/ProductEdit.html'
    })
    .otherwise({
        redirectTo: '/'
    });
    console.log('routing done');
});

3 个答案:

答案 0 :(得分:1)

更改你的htmt

&#13;
&#13;
var angSPA = angular.module('angSPA', []);

angSPA.controller("ProductController", function($scope, ProductFactory) {
    $scope.products = [];
    var init = function() {
        $scope.products = ProductFactory.getProducts();
        console.log('got products in controller');
        console.log($scope.products + "")
    };
    init();
   
});


angSPA.factory('ProductFactory', function() {
    var products = [
        {code: 1, name: 'Game of Thrones', description: 'Series'},
        {code: 2, name: 'DmC', description: 'Game'},
        {code: 3, name: 'Matrix', description: 'Movie'},
        {code: 4, name: 'Linkin Park', description: 'Music Band'}];

    var factory = {};
    console.log('initializing factory');
    factory.getProducts = function() {
        console.log('factory now providing products');
        return products;
    };

    factory.loadProductByCode = function(code) {
        var product;
        for (var i = 0; i < products.length; i++) {
            if (products[i].code == code) {
                product = products[i];
                return product;
            }
        }
    };

    factory.saveProduct = function(product) {
        products.push(product);
        console.log('factory saved product');
    };

    factory.deleteProduct = function(code) {
        var product = factory.loadProductByCode(code);
        if (product != null) {
            products.remove(product);
            console.log('factory deleted product');
        }
    };
    console.log('returning factory');
    return factory;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>

<body  ng-app="angSPA" ng-controller="ProductController">
        <div class="container">
            <h2 class="page-title">Product Listing</h2>
            <div class="searchbar">
                <ul class="entity-tabular-fields">
                    <li>
                        <label>Search: </label>
                        <span class="field-control">
                            <input type="text" data-ng-model="filter.productName" />
                        </span>
                        <label></label>
                    </li>
                </ul>
            </div>
            <h2><a href="#/ProductEdit">Add New Product</a></h2>
            <table class="items-listing">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    <tr data-ng-repeat="prod in products|filter:filter.productName">
                        <td ></td>
                        <td><a href="#/ProductEdit?code={{prod.code}}">{{prod.code}}</a></td>
                        <td>{{prod.name}}</td>
                        <td>{{prod.description}}</td>
                        <td><a href="#/?code={{prod.code}}">Delete</a></td>
                    </tr>
                </tbody>
            </table>
        </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你的ng-repeat指令应该在tr元素而不是td。

<tr data-ng-repeat="product in products|filter:filter.productName">

不是您的问题的原因,但要登录服务或控制器,您可以使用$ log服务和stringify来序列化您的对象。

$log.debug(JSON.stringify($scope.products));

答案 2 :(得分:0)

查看代码,您可以在开头$scope.products = []。这将使角度观察成为空阵列。

在init函数中,将products数组分配给$ scope.products。但由于角度仍然在观察初始阵列,因此它不会意识到这种变化。

解决方案是删除初始赋值$scope.products = []并确保更改原始数组但从未将其设置为新数组。

BTW:您可以console.log(JSON.stringify($scope.products))获取更好的日志信息。