如何从父控制器引用子作用域

How to reference the child scope from the parent controller?

本文关键字:引用 作用域 控制器      更新时间:2023-09-26

下面的代码只是显示一个窗体,并使用editDownload方法保存输入:

.JS:

$scope.editDownload = function(downloadId) {
  var Download = Parse.Object.extend('Download')
  var download = new Download()
  var data = {
    'title': $scope.download.title,
    'link': $scope.download.link
  }
  download.save(data, {
    success: function(result) {
      console.log('Success:', result.toJSON())
    },
    error: function(result, error) {
      alert('Error:', error.message)
    }
  })
}

.HTML:

<ul class="text-center no-bullet">
  <li ng-repeat="download in downloads">
    <form>
      <input type="text" class="form-control" ng-model="download.title">
      <input type="text" class="form-control" ng-model="download.link">
      <button type="button" class="btn btn-primary" ng-click="editDownload('{{download.objectId}}')">Submit</button>
    </form>
  </li>
</ul>

但是,有一个问题,$scope.download.title$scope.download变得undefined因为它们的值是在ng-repeat内设置的,因此在不同的范围内。

如何从父控制器引用此"子"作用域?

注意:我无法在模板中执行$parent.download.title$parent.download.link,因为这样ng-model将不会显示任何内容(它将不再引用ng-repeat中的子项。

您不必通过表达式将参数传递给editDownload()。你可以通过editDownload(download.objectId).

生成的按钮标记如下所示:

<button type="button" class="btn btn-primary" ng-click="editDownload(download.objectId)">Submit</button>

此外,$scope.download 不是指 ng-repeat中的download

如果要对要传递editDownload() download对象执行某些操作,则可以将对象本身作为参数传递即可。

editDownload(download)

而不是传递download.objectId作为参数。

最后,它应该看起来像这样:

<button type="button" class="btn btn-primary" ng-click="editDownload(download)">Submit</button>