我们如何在嵌套控制器范围内将 ng-model 变量设置为父控制器 [英] How we set to ng-model variable to parent controller in nested controllers scope

查看:35
本文介绍了我们如何在嵌套控制器范围内将 ng-model 变量设置为父控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套在另一个控制器作用域中的 ng-controller.我想将嵌套控制器范围中的范围变量设置为父控制器.我有观点:

<input type="text" ng-model="name"/><div ng-controller="CountryDataController"><完整的(……)selectedObject="国家"/>

这是表格的一部分.然后在表单提交时,我想从 MyCtrl(名称,国家/地区)发送 ng-models 做:

fields: {name: $scope.name,国家:$scope.country,},

我如何知道 angular,selectedObject 模型属于 MyCtrl,而不是 CountryDataController.我试过

selectedObject="MyCtrl.country"selectedObject="国家[MyCtrl]"

但没有效果.

angucomplete 中的 selectedObject 与 ng-model 类似.此外,我不想将 CountryDataController 的逻辑重写为 MyCtrl,因为首先我有用于自动完成和第二个文件上传的字段.

是否有任何约定?

解决方案

你可以使用 $parent,但是如果你移动你的 HTML 或者最终添加另一个控制器,它会中断.

正确的做法是使用controller as语法,如下所示:

<!-- 使用 topCtrl 访问这个控制器作用域 --><div ng-controller="MyCtrl as topCtrl"><input type="text" ng-model="name"/><!-- 使用 countryCtrl 访问此控制器范围 --><div ng-controller="CountryDataController as countryCtrl"><完整的(……)selectedObject="topCtrl.country"/>

I have one ng-controller nested in another controllers scope. I want to set scope variable in nested controller scope, to parent controller. I have view:

<div ng-controller="MyCtrl">
    <input type="text" ng-model="name"/>
    <div ng-controller="CountryDataController">
        <angucomplete
        (...)
        selectedObject="country"/>
    </div>
</div>

which is part of the form. Then on form submit i want to send ng-models from MyCtrl ( name,country) doing:

fields: {name: $scope.name, 
        country: $scope.country,
        },

How can i tell angular, that selectedObject model belongs to MyCtrl, and not CountryDataController. I tried

selectedObject="MyCtrl.country"
selectedObject="country[MyCtrl]"

but without effects.

selectedObject in angucomplete works like ng-model. Also I don't want to rewrite logic from CountryDataController to MyCtrl, because in first i have fields for autocomplete and in second file uploading.

Is there any convention for this?

解决方案

You can use $parent, but if you move your HTML or eventually add another controller it between it will break.

The correct way to do that is to use the controller as syntax, as shown below:

<!-- use topCtrl to access this controller scope -->
<div ng-controller="MyCtrl as topCtrl">
  <input type="text" ng-model="name"/>
  <!-- use countryCtrl to access this controller scope -->
  <div ng-controller="CountryDataController as countryCtrl">
      <angucomplete
      (...)
      selectedObject="topCtrl.country"/>
  </div>
</div>

这篇关于我们如何在嵌套控制器范围内将 ng-model 变量设置为父控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆