Angular中的新对象永久绑定到模板元素

时间:2013-11-21 20:22:36

标签: angularjs angularjs-scope angularjs-ng-repeat

我有一个小型的Angular项目,它实现了一个Controller:

concernsApp.factory('ConcernService', function ($http, $q) {
var api_url = "http://localhost:8000/api/";

var ConcernService = {

    ...

    save: function (url, obj) {
        console.log(obj)
        var defer = $q.defer();
        $http({method: 'POST',
            url: api_url + url,
            data: obj}).
            success(function (data, status, headers, config) {
                defer.resolve(data);
            }).error(function (data, status, headers, config) {
                defer.reject(status);
            });
        return defer.promise;
        },
    };
    return ConcernService;
});


concernsApp.controller('ProjectsCtrl', function ($scope, $http, ConcernService) {

    ...

    $scope.createProject = function(new_project) {
        ConcernService.save('projects/', new_project).then(function(){
            $scope.projects.push(new_project);
        });
    };

html模板:

<div ng-controller="ProjectsCtrl" ng-init="getProjects(); getTasks(); new_project = {};">
    <div class="row col-lg-8">
      <h2>Projects</h2>
      <input type="text" ng-model="search_projects" class="form-control" style="width:300px; margin: 30px 0px">

      <table class="table table-bordered col-lg-8" ng-repeat="project in projects | orderBy: 'id' | limitTo: 10 | filter:search_projects">
        <tr>
            <td class="col-lg-4">
                <h3>{{ project.id }}</h3>
                <h4>{{ project.title }}</h4>
            </td>
            <td class="col-lg-2">
                <a href="#" ng-click="deleteProject(project)">Delete Project</a>
            </td>
        </tr>
      </table>
    </div>
   <div class="row">
     <div class="col-lg-8">
       <h2>Create a New Project</h2>
       <form class="form-horizontal">
         <div class="control-group">
           <label class="control-label" for="id_title">Title</label>
             <div class="controls">
               <input type="text" id="title" class="form-control" placeholder="Title" ng-model="new_project.title">
             </div>
           </div>
         </form>
        <br />
        <button class="btn btn-success" ng-click="createProject(new_project)">create</button>
     </div>
   </div>
 </div>

因此,成功提交到API后,代码会将new_project对象推送到$scopes.projects,这很有用。但是,当我开始在创建项目标题输入字段中键入时,它似乎绑定到上一个新项目,并且该项目的标题开始随时更改。

这显然也会阻止任何进一步的新项目对象的创建。我对Angular很新,我不确定这里发生了什么,或者如何解决它。基本上我想继续创建新项目并将它们推送到阵列。

1 个答案:

答案 0 :(得分:1)

您在new_project = {}中设置ng-init,只有在将指令放入DOM时才会发生一次。

createProject功能中,您可以将其重置为{}以制作 new_project

$scope.createProject = function(new_project) {
    ConcernService.save('projects/', new_project).then(function(){
        $scope.projects.push(new_project);
        $scope.new_project = {};
    });
};

作为旁注,我也会将new_project = {}的定义移到控制器上。

作为Angular的一般禅宗:

将范围视为模板中的只读和控制器中的只写