0

我有一个用于在部分中创建新记录的表单,我将其加载到我的主视图中,如下所示

<div ng-controller="NewProductController">
  <ng-include src=" 'views/partials/product-form.html' "></ng-include>
</div>

在表单中,我有一些输入字段

..
<input ng-model="cip" type="text" id="cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>
<input ng-model="name" type="text" id="name" class="form-control" placeholder="Enter the name" />

在我的控制器中,我正在发送一个带有输入字段值的 POST 请求:

...
.controller('NewProductController', function(Product, $scope) {

  $scope.create = function () {
    Product.create( {'cip': $scope.cip,
                     'name': $scope.name,
                     'dosage': $scope.dosage,
                     ...
                     });
    };

问题是当输入字段的值发生变化时,它不会反映在控制器中($scope.cip 和 $scope.name 是未定义的,除非我用一些值初始化它们)但是当 $scope.cip 和 $scope.名称在控制器中更改,更改正确反映在视图中。

我认为这种更新是自动的还是我错过了什么?

4

1 回答 1

1

发生这种情况的原因是ng-include创建了一个子范围。由于您在子范围内(即模板 html 内)管理模型字段,因此这些字段在定义控制器的父范围内不可用。

要解决此问题,您首先需要做的是创建一个 objproduct并在控制器NewProductController范围内定义它。

$scope.product={};

然后模板应该绑定到这个产品对象的子属性。

<input ng-model="product.cip" type="text" id="cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>

现在您的更改将在父产品对象中可用。

您可以通过使用这样的product对象来改进它ng-init

<ng-include src=" 'views/partials/product-form.html' " ng-init='model=product'></ng-include>

现在您的模板输入字段更改为

<input ng-model="cip" type="text" id="model.cip" class="form-control" placeholder="Enter the CIP" autofocus="autofocus"/>

优势 您的模板不依赖于父模型类的结构。依赖是明确的。模板变得更加可重用,因为它清楚地定义了它使用的模型,就像在您的情况下模板使用Product模型一样。

为了答案的完整性,我必须链接到这篇必读文章,了解范围

于 2013-08-24T12:16:48.793 回答