AngularJS模型中的getter setter

时间:2014-12-06 08:01:32

标签: javascript angularjs getter-setter

我有以下标记

 <div ng-app="" ng-controller="x">
    <label>Name</label>
    <input type="text" name="name" ng-model="newCustomField.name"/>
    <label>Is Required?</label>
    <input type="checkbox" class="form-control" name="IsRequired" value="true" ng-model="newCustomField.IsRequired" />
    <input type="button" value="Save" ng-click="saveRecord()" />
</div>

和以下脚本

var empid = 1;
function x($scope) {
    $scope.customFields = [{ id: 0, 'name': 'Professional', 'IsRequired': true }];
    $scope.saveRecord = function () {
         $scope.newCustomField.id = empid++;
         if($scope.newCustomField.IsRequired == undefined)
             $scope.newCustomField.IsRequired = false;

         $scope.customFields.push($scope.newCustomField);
         $scope.newCustomField = {};
    }
}

我可以使用某种defineProperty,这样我就不必进行未定义检查了吗?

我的意思是我可以拥有以下内容吗?如果没有,可以选择什么。

function x($scope) {
    Object.defineProperty($scope.newCustomField, 'IsRequired', {
       get: function() {
           return this._IsRequired;
       },
       set: function(name) {
          if(name == undefined || name == null)
              this._IsRequired = false;
          else 
              this._IsRequired = true;
    }
    $scope.customFields = [{ id: 0, 'name': 'Professional', 'IsRequired': true }];
    $scope.saveRecord = function () {
         $scope.newCustomField.id = empid++;
         //if($scope.newCustomField.IsRequired == undefined)
           //  $scope.newCustomField.IsRequired = false;
         $scope.customFields.push($scope.newCustomField);
         $scope.newCustomField = {};
    }
}

0 个答案:

没有答案