AngularJS:如何从ui-grid单元格模板中访问作用域?

41

如何从ui-grid单元格模板中访问$scope?这是我的控制器代码:

app.controller('MainCtrl', ['$scope', function ($scope) {

  // i want to reference this from a cell template.
  $scope.world = function() { return 'world'; };

  $scope.gridOptions = {
    data: [
      { id: "item1" },
      { id: "item2" }
    ],
    columnDefs: [
    {
      field: 'id',

      // world() is never called and is not displayed.
      cellTemplate: '<div>{{ "hello " + world() }}</div>'
    }]
  };
}]);

在这里查看它的实际效果:http://plnkr.co/edit/WYXeQShHWKDYDs4MIZnP?p=preview

我期望单元格内容显示为“hello world”,但它们只显示“hello”。

1个回答

70
根据http://ui-grid.info/docs/#/tutorial/305_appScope,该网格拥有独立的作用域,因此您需要使用grid.appScope来访问应用程序作用域。 解决方案是将单元格模板更改为:
  cellTemplate: '<div>{{ "hello " + grid.appScope.world() }}</div>'

2
我必须使用“col.grid.appScope.<ctrl alias>.myFunction()”来过滤表头模板。 - user2171669
<ctrl alias> 究竟是什么?根据上面的例子来说呢? - user2227400
1
我不能确定,但是带有<ctrl alias>的注释似乎对那些使用“Controller as”语法的人有意义。因此,如果您已将控制器设置为可用作别名(通常为:controller as vm),则需要在链中包含该别名,例如:grid.appScope.vm.myMethod()。希望能有所帮助。 - FOR
我尝试了这个 ng-change="grid.appScope.checkValidaton($event,MODEL_COL_FIELD,true,true)。虽然作用域函数被调用,但是参数是未定义的。我该如何传递 $eventng-model - Saurabh Tiwari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接