【问题标题】:angularjs: after ng-model $scope.resource looks not the sameangularjs:在 ng-model $scope.resource 之后看起来不一样
【发布时间】:2013-03-12 07:37:11
【问题描述】:

我的控制器中有两个功能。

  • showEditScreen 函数实际加载用户记录 $resource.get
  • 应该更新用户的updateUserDetails 函数。

showEditScreen 函数中一切正常。用户详细信息通过 json 解析,并且在查看 $get$post$update$scope.user 对象函数时存在。

updateUserDetails 函数中查看相同(也未修改)的对象时,该对象已更改,并且所有函数(如$get$post$update 等)都丢失了。

这是一个非常奇怪的行为。有人对此有解释吗?

当我使用 http.put 时,我可以顺便保存对象。

showEditScreen() 函数中的console.log($scope.user) 输出

Resource {$get: function, $save: function, $query: function, $remove: function, $delete:      function…}
firstName: "Mista"
id: "d419375a-ba0b-4177-93cf-842e2c3e046e"
lastName: "BlaaahBlaaah1"
password: "bla"
roles: Array[2]
username: "blabla1"
__proto__: Resource

console.log($scope.user) in updateUserDetails() 函数:

Resource {id: "d419375a-ba0b-4177-93cf-842e2c3e046e", firstName: "Mista", lastName: "BlaaahBlaaah1", username: "blabla1", password: "bla"…}
firstName: "Mista"
id: "d419375a-ba0b-4177-93cf-842e2c3e046e"
lastName: "BlaaahBlaaah1"
password: "bla"
roles: Array[2]
username: "blabla1"
__proto__: Resource

在 updateUserDetails() 函数中执行 $scope.user.$update() 时:

POST http://localhost:8080/api/user/.json 405 (Request method 'POST' not supported)      angular.js:9120
(anonymous function) angular.js:9120
sendReq angular.js:8977
$http angular.js:8768
Resource.(anonymous function) angular-resource.js:385
Resource.(anonymous function) angular-resource.js:431
UserCtrl.$scope.updateUserDetails controllers.js:37
(anonymous function) angular.js:6212
(anonymous function) angular.js:12751
Scope.$eval angular.js:7905
Scope.$apply angular.js:7985
$delegate.__proto__.$apply index.html:500
(anonymous function) angular.js:12750
(anonymous function) angular.js:1928
forEach angular.js:110
eventHandler angular.js:1927

HTML:

<div id="user_list" class="listview_list">
<div id="user_row" class="listview_row" ng-repeat="user in users">
    <div id="user_username" class="listview_column"><span class="listview_fat">   {{user.username}}</span></div>
    <div id="user_firstname" class="listview_column">{{user.firstName}}</div>
    <div id="user_lastname" class="listview_column">{{user.lastName}}</div>
    <button class="listview_row_button" ng-click="showEditScreen(user.id)">Edit</button>
</div>
</div>

<div id="user_edit" class="edit_form" ng-show="userEditScreenIsVisible">
<form name="edit_user">
    <label>Username</label><br/>
    <input name="username" ng-model="user.username" required/><br/>
    <label>Firstname</label><br/>
    <input name="firstName" ng-model="user.firstName" required/><br/>
    <label>Lastname</label><br/>
    <input name="lastName" ng-model="user.lastName" required/><br/>
    <button class="button" ng-click="hideEditScreen()">Close</button>
    <button class="button" ng-click="updateUserDetails()">Update</button>
</form>
</div>

控制器:

/*
* Controller to display and manipulate users.
*/
function UserCtrl($scope, $http, Users, User) {
// set edit screen to invisible by default
$scope.userEditScreenIsVisible = false;

// set new screen to invisible by default
$scope.userNewScreenIsVisible = false;

// display list with users
Users.query(
    {}, //params
    function (data) { //success
        $scope.users = data.data;
    },
    function (data) { //failure
        console.log("Error occurred while getting list of users");
    });

// show edit screen if edit button is clicked
$scope.showEditScreen = function(id) {
    $scope.user = User.get({userId: id});
    console.log($scope.user);
    $scope.userEditScreenIsVisible = true;
}

// hide edit screen if close button is clicked
$scope.hideEditScreen = function() {
    $scope.userEditScreenIsVisible = false;
}

$scope.updateUserDetails = function() {
    console.log($scope.user);
    $scope.user.$update();
    //$http.put("http://localhost:8080/api/user/" + $scope.user.id + ".json", $scope.user);
}

// show new screen if add button is clicked
$scope.showNewScreen = function() {
    $scope.userNewScreenIsVisible = true;
}
}

服务:

angular.module('user.services', ['ngResource']).
factory('Users', function($resource) {
    return $resource('http://localhost\\:8080/api/user/all.json', {}, {
        query: {method:'GET', params:{}, isArray:false}
    });
}).
factory('User', function($resource){
    return $resource('http://localhost\\:8080/api/user/:userId.json', {}, {
       get: {method:'GET'},
       update: {method:'PUT'}
    });
})

问题已解决!!!!

服务:

// User Service
angular.module('user.services', ['ngResource']).
factory('User', function($resource){
    return $resource('/api/user/:userId', {userId: '@id'}, {
       query: {method: 'GET', headers: [{'Content-Type': 'application/json'}, {'Accept'  : 'application/json'}]},
       get: {method:'GET', headers: [{'Content-Type': 'application/json'}, {'Accept' :  'application/json'}]},
       update: {method:'PUT', headers: [{'Content-Type': 'application/json'}, {'Accept'  : 'application/json'}]}
    });
})

【问题讨论】:

  • 您如何确定第二次不会出现 Resource 函数? console.log 可以裁剪字符串。在 Firebug 中,查看可通过 about:config 编辑的stringCropLength preference
  • Vineet 是对的,这些功能在更远的地方可用。我删除了 .json 扩展名并添加了内容类型标头。它现在正在工作。
  • 请将您的解决方案添加为答案并接受它(这样该问题将不再显示在“未回答”列表中)。
  • 完成。现在应该有用了:)

标签: angularjs angularjs-scope


【解决方案1】:

Vineet 解决了第一个问题。实际上存在 $get、$post、$delete 等函数。在 Chrome Batarang 环境中扩展日志记录时再往下走。

我的实际问题是默认查询方法不喜欢文件扩展名,例如.json

如果使用文件扩展名,在不解析 Id 时会发生以下情况:

  • /api/user/.json

但我们希望有以下显示所有用户:

  • /api/user/

因此不应使用文件扩展名。 Content-Type 应通过标头协商。这样就不需要文件扩展名来确定 Content-Type。

我通过以下方式更改了我的 user.service:

angular.module('user.services', ['ngResource']).
factory('User', function($resource){
    return $resource('http://localhost\\:8080/api/user/:userId', {userId: '@id'}, {
       query: {method: 'GET', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
       get: {method:'GET', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
       update: {method:'PUT', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
       create: {method:'POST', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
       delete: {method:'DELETE', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]}
    });
})

我的控制器如下所示:

function UserCtrl($scope, $resource, User) {
// set edit screen to invisible by default
$scope.userModScreenIsVisible = false;

// initialize buttons as invisible
$scope.updateUserDetailsButtonIsVisible = false;
$scope.saveUserDetailsButtonIsVisible = false;

// display list with users
$scope.getList = function() {
    User.query(
        {}, //params
        function (data) { //success
            $scope.users = data.data;
        },
        function (data) { //failure
            console.log("Error occurred while getting list of users");
        });
}
$scope.getList();

// show edit screen if edit button is clicked
$scope.showEditScreen = function(id) {
    $scope.user = User.get({userId: id});
    $scope.updateUserDetailsButtonIsVisible = true;
    $scope.userModScreenIsVisible = true;
}

// hide edit screen if close button is clicked
$scope.hideEditScreen = function() {
    $scope.updateUserDetailsButtonIsVisible = false;
    $scope.saveUserDetailsButtonIsVisible = false;
    $scope.userModScreenIsVisible = false;
}

// update a user
$scope.updateUserDetails = function() {
    $scope.user.$update();
    for(var i=0;i<$scope.users.length;i++) {
        if($scope.users[i].id == $scope.user.id) {
            angular.extend($scope.users[i], $scope.user);
            break;
        }
    }
    console.log($scope.user);
    //$scope.user = User.get({userId: $scope.user.id});
    $scope.updateUserDetailsButtonIsVisible = false;
    $scope.userModScreenIsVisible = false;
}

// show a new user screen
$scope.showNewScreen = function() {
    $scope.user = new User();
    $scope.saveUserDetailsButtonIsVisible = true;
    $scope.userModScreenIsVisible = true;
}

// save a new user
$scope.saveUserDetails = function() {
    $scope.user.$create();
    $scope.users.push($scope.user);
    $scope.saveUserDetailsButtonIsVisible = false;
    $scope.userModScreenIsVisible = false;
}

// delete a user
$scope.deleteUser = function(id) {
    $scope.user = User.get({userId: id});
    $scope.user.$delete();
}
}

HTML:

<div id="user_list" class="listview_list">
<div id="user_row" class="listview_row" ng-repeat="u in users">
    <div id="user_username" class="listview_column"><span class="listview_fat">{{u.username}}</span></div>
    <div id="user_firstname" class="listview_column">{{u.firstName}}</div>
    <div id="user_lastname" class="listview_column">{{u.lastName}}</div>
    <button class="listview_row_button" ng-click="deleteUser(u.id)">Delete</button>
    <button class="listview_row_button" ng-click="showEditScreen(u.id)">Edit</button>
</div>
</div>
<div id="user_new" class="new_user">
<button class="new_user_button" ng-click="showNewScreen()">Add user</button>
</div>

<div id="user_mod" class="mod_form" ng-show="userModScreenIsVisible">
<form name="mod_user">
    <label>Username</label><br/>
    <input name="username" ng-model="user.username"/><br/>
    <label>Firstname</label><br/>
    <input name="firstName" ng-model="user.firstName"/><br/>
    <label>Lastname</label><br/>
    <input name="lastName" ng-model="user.lastName"/><br/>
    <button class="button" ng-click="hideEditScreen()">Close</button>
    <button class="button" ng-click="updateUserDetails()" ng-show="updateUserDetailsButtonIsVisible">Update</button>
    <button class="button" ng-click="saveUserDetails()" ng-show="saveUserDetailsButtonIsVisible">Save</button>
</form>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    相关资源
    最近更新 更多