0

我有一个使用资源创建和使用 APIRest 列出的代码,我需要将一个 Id 从模板传递到控制器,从控制器传递到服务。

这是我的代码:

模板.html

<div class="industrialists" ng-app="cliConsApp">
    <ul class="table" ng-controller="industrialistCtrl" ng-init="init('{{ constructionPrivateInformationId }}')">
        <form name="myForm">
            <input type="text" id="userName" ng-model="industrialist.user" placeholder="User name"/>
            <input type="text" id="jobName" ng-model="industrialist.job" placeholder="Job name"/>
            <a ng-click="createNewUser()" class="btn btn-small btn-primary">create new user</a>
        </form>

        <li ng-repeat="industrial in industrialists">
            [[industrial.job.name]]
        </li>
    </ul>
</div>

应用程序.js

var cliConsApp = angular.module('cliConsApp',['uTrans', 'cliConsApp.controllers', 'cliConsApp.services' ]).
    config(function($interpolateProvider){
        $interpolateProvider.startSymbol('[[').endSymbol(']]');
    }
);;

服务.js

var services = angular.module('cliConsApp.services', ['ngResource']);

services.factory('IndustrialistsFactory', function ($resource) {
    return $resource(
        '/app_dev.php/api/v1/constructionprivateinformations/:id/industrialists',
        {id: '@id'},
        {
            query: { method: 'GET', isArray: true },
            create: { method: 'POST'}
        }
    )
});

控制器.js

var app = angular.module('cliConsApp.controllers', []);

app.controller('industrialistCtrl', ['$scope', 'IndustrialistsFactory',

    function ($scope, IndustrialistsFactory) {

        $scope.init = function (id) {

            $scope.id=id;
            $scope.industrialists= IndustrialistsFactory.query({},{id: $scope.id});

            $scope.createNewUser = function (id) {
                IndustrialistsFactory.create($scope.industrialist, {id: $scope.id});
                $scope.industrialists = IndustrialistsFactory.query({id: $scope.id});

            }
        }
}]);

我在 CreateNewUser 中遇到问题,因为服务未接收 id 且 url 不正确。

我该怎么做?

4

1 回答 1

0

我发现您的代码存在重大问题。您不是直接在控制器内部而是在 init 函数内部声明了模型。这限制了它们的范围并破坏了ng-click="createNewUser()". 将它们移出:

app.controller('industrialistCtrl', ['$scope', 'IndustrialistsFactory',
    function ($scope, IndustrialistsFactory) {
        $scope.id = "";

        $scope.industrialists = [];

        $scope.createNewUser = function (id) {
            // update the models here
        }

        $scope.init = function (id) {
            // update the models here
        }
}]);
于 2013-11-20T15:12:06.577 回答