当视图字段为空时,通过视图生成 angular 个模型属性

Generate angular model properties by view, when view fields are empty

我有这样的控制器:

function ($scope) {
    $scope.Package = {};

    $scope.CreatePackage = function () {
        console.log($scope.Package);
    };
}

并像这样查看:

<input type="text" ng-model="Package.Name" />

<input type="number" ng-model="Package.Price" min="0" step="0.5" />

<button ng-click="CreatePackage()">Create New Package</button>

所以,当我点击这个按钮而不输入包裹名称和价格时,我希望我的模型是:

{ Name: null, Price: null }

{ Name: '', Price: '' }

默认。

如何自动生成?有没有 angular 选项可以做到这一点?

// Code goes here
angular.module("myApp", [])
  .controller("myCtrl", function($scope) {
    $scope.Package = {};
    $scope.CreatePackage = function() {
      
      if (!$scope.Package.Name && !$scope.Package.Price) {
        $scope.Package = {
          Name: '',
          Preis: ''
        };
      }
      console.log($scope.Package);
    };
  })
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script data-require="angular.js@1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="myCtrl">
  <input type="text" ng-model="Package.Name" />

  <input type="number" ng-model="Package.Price" min="0" step="0.5" />

  <button ng-click="CreatePackage()">Create New Package</button>
</body>

</html>

这是一个笨蛋demo

您最初可以在 $scope.Package 对象中定义名称和价格属性。绑定空字符串将导致 {Name: "", Price: ""} 成为 CreatePackage 函数中的 $scope.Package 对象。

$scope.Package = {
    Name:'',
    Price:''
};

希望对您有所帮助