Angularjs 从模板到控制器和从控制器到服务的角度传递参数

Angularjs 从模板到控制器和从控制器到服务的角度传递参数,angularjs,angularjs-scope,angular-resource,Angularjs,Angularjs Scope,Angular Resource,我有一个代码,使用资源创建和列表使用APIRest,我需要传递一个Id从模板到控制器,从控制器到服务 这是我的代码: Template.html <div class="industrialists" ng-app="cliConsApp"> <ul class="table" ng-controller="industrialistCtrl" ng-init="init('{{ constructionPrivateInformationId }}')">

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

这是我的代码:

Template.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>
services.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'}
        }
    )
});
controllers.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不正确


我该怎么做?

我发现您的代码有一个主要问题。您不是直接在控制器中声明模型,而是在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
        }
}]);
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
        }
}]);