AngularJs - 使用$ parent ng-model从控制器更改/推送选择颜色

时间:2013-03-19 02:34:34

标签: javascript angularjs

这是一个非常简单的例子: JsFiddle

这是MainCtrl

function MainCtrl($scope)
   {
   $scope.color = {};
   $scope.colors = [
       { name: "red" },
       { name: "yellow" },
   ];

 var newColor = $scope.color;
    newColor.name = "blue";  
$scope.colors.push(newColor);
$scope.selectedColor = newColor;

}

我有3个html表单:

  1. MainForm.Html
  2. AvailableColors.html(部分,使用ng-include嵌入MainForm.html)
  3. AddNewColor.html
  4. MainForm.Html如下所示:

    <div ng-app ng-controller="MainCtrl">
     <div ng-include="'AvailableColors.html'">
    </div>
    

    AvailableColors.html如下所示:

    <select ng-model="$parent.selectedColor" ng-options="color.name for color in colors">
      <option value="" selected>Select Color ..</option>  
    </select>
    <a href="#">Add New Color</a>
    <br />
    value is {{ selectedColor }}
    

    在JsFiddle示例中,我试图模拟用户添加新颜色。我需要AvailableColors的ng-model有'$ parent'。因为它来自ng-include和w / o'$ parent',所选择的选择将不在表单提交范围内。

    我的问题是,当用户添加时,我无法将新添加的颜色推送到AvailableColors.html。

    有什么想法吗?

    一个注意事项:我知道在JsFiddle中添加了新的颜色'blue',但那是因为在该示例中确实没有ng-include。

    显然,当实际存在ng-include时,它不会出现,不会刷新页面。

2 个答案:

答案 0 :(得分:1)

父母只读儿童。要做你想做的事,你将不得不使用父控制器中的方法。

    $scope.setSelected = function(color) {
        $scope.selectedColor = color;
    }

    $scope.addColor = function(newColor) {
       $scope.colors.push(newColor);
    }

然后,您可以使用包含的html中的输入:

//Selector
<select ng-click="setSelected(selectColor)" ng-model="selectColor" ng-options="color.name for color in colors">
  <option value="" selected>Select Color ..</option>
</select>

//Add control
<input type="text" ng-model="newColor.name" />
<button id="addBtn" ng-click="addColor(newColor)">Add</button>

正如您所看到的,我在选择中添加了ng-click以更新父级。

答案 1 :(得分:0)

如果您使用$ scope(as recommended by the Angular team)上的对象引用,则不必在任何地方使用$parent

$scope.model = {selectedColor: ''};  // use an object here
$scope.addColor = function(newColorName) {
  $scope.colors.push({name: newColorName});
};

AvailableColors.html:

<select ng-model="model.selectedColor" ng-options="color.name for color in colors">
   <option value="" selected>Select Color ..</option>  
</select>
<br>
<input type="text" ng-model="colorName">
<button ng-click="addColor(colorName); colorName=''">Add</button>
<br />
value is {{ model.selectedColor }}

Plunker,使用ng-include。