将属性赋值给控制器中的$ scope

时间:2015-04-18 14:42:29

标签: angularjs

我在AngularJs中遇到一个小问题:

我想为$ scope.customer.LikeProfile分配一个静态

$scope.customer.LikeProfil = 0;

我试图在我的视图页面上的window.alert中显示该值

window.alert($scope.customer.LikeProfil);

这条指令转过我并在浏览器的控制台上显示错误:

TypeError:无法设置属性' LikeProfil'未定义的     at k。$ scope.addIdea

我想在控制器中做的是使用$ resource将新客户(对象)添加到数据库,这是我的代码

controller.js:

app.controller('CustomerCreationCtrl', ['$scope','PostCustomerFactory', '$location',
function ($scope, PostCustomerFactory, $location) {
  $scope.createNewCustomer = function(){
      $scope.customer.LikeProfil = 0;
    window.alert($scope.customer.LikeProfil);
    $scope.customer.FirstName = "Rochdi (Name by default";
      PostCustomerFactory.create($scope.customer);
      $location.path("/customers");
  };
}]);

service.js

services.factory('PostIdeaFactory', function ($resource) {
    return $resource(url + '/ideaService/postIdea', {}, {
        create: { method: 'POST' }
    });
});

添加-view.html

<div class="form-group">
      <label for="inputBirthDate" class="col-md-2 control-label">Birth of Date</label>
      <div class="col-md-10">
          <input type="date" class="form-control input-sm" id="inputBirthDate" placeholder="..." ng-model="customer.BirthDate">
      </div>
    </div>
    <div class="form-group">
       <label for="inputPseudo" class="col-md-2 control-label">Pseudo</label>
       <div class="col-md-10">
          <input type="text" class="form-control input-sm" id="inputPseudo" placeholder="..." ng-model="customer.Pseudo">
        </div>
      </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
           <button type="submit" class="btn btn-info btn-sm m-t-10" ng-click="createNewCustomer()">SUBMIT FORM</button>
         </div>
     </div>

对于Pseudo和BithDate,他们只是客户的属性,我的目标是为LikeProfil和FirstName属性分配一个静态值,并在视图中的弹出框(window.alert)中显示它们,不关心Pseudo和BithDate属性它不是我的问题而且它们有效

谢谢

1 个答案:

答案 0 :(得分:4)

在将属性设置为某个内容之前,您需要先将customer定义为object

$scope.customer ={};

你的最终代码是(controller.js)

app.controller('CustomerCreationCtrl', ['$scope','PostCustomerFactory', '$location',
function ($scope, PostCustomerFactory, $location) {
 $scope.customer ={};
  $scope.createNewCustomer = function(){
      $scope.customer.LikeProfil = 0;
    window.alert($scope.customer.LikeProfil);
    $scope.customer.FirstName = "Rochdi (Name by default";
      PostCustomerFactory.create($scope.customer);
      $location.path("/customers");
  };
}]);