angularjs - 如何在 angularJS 中不使用 $scope 将对象从 Controller 传递到指令

标签 angularjs angularjs-directive

骗子链接:http://plnkr.co/edit/j7BeL72lwHISCIlwuAez?p=preview

在上面的链接中,我使用 $scope 来传递数据。但我想使用模型方法并将MainController中的$scope.data替换为this.data

var app = angular.module('plunker', []);

app.controller('MainCtrl', ['$scope',
  function($scope) {
    $scope.data = [{
      time: '8/19/2014',
      id: 123,
      text: 'first'
    }, {
      time: '8/18/2014',
      id: 456,
      text: 'second'
    }, {
      time: '8/17/2014',
      id: 123,
      text: 'third'
    }];
  }
]);

app.directive('scrollGrid', [

  function() {
    return {
      restrict: 'AE',
      scope: {
        data: '='
      },
      templateUrl: 'mainScroll.html',
      controller: 'gridController',
      controllerAs: 'gridCtrl'
    }
  }
]);

app.controller('gridController', ['$scope',
  function($scope) {}
])

最佳答案

您可以在此处阅读有关“ Controller 作为语法”的更多信息: http://toddmotto.com/digging-into-angulars-controller-as-syntax/

请注意此语法是在 Angular 1.2 中引入的。你的 plunkr 使用的是 Angular 1.0.x。

这是示例 plunkr:http://plnkr.co/edit/5ddLyuRlyCt4PqulpOJG

标记已修改如下:

<body ng-controller="MainCtrl as ctrl">
    {{ctrl.data}}
    <scroll-grid data="ctrl.data"></scroll-grid>
</body>

Controller 已修改如下:

app.controller('MainCtrl', function() {
    this.data = [
        {
            time: '8/19/2014',
            id : 123,
            text : 'first'
        },
        {
            time: '8/18/2014',
            id : 456,
            text : 'second'
        },
        {
            time: '8/17/2014',
            id : 123,
            text : 'third'
        }
    ];
});

如果仍然遇到问题,请告诉我

关于angularjs - 如何在 angularJS 中不使用 $scope 将对象从 Controller 传递到指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25392727/

相关文章:

angularjs - Angular2 构建错误 - 找不到类型

javascript - @Injectable 装饰器基本上相当于 Spring 中的 @Component 或 @Autowired 的 Angular 2 吗?

javascript - 在指令中访问 child 的 '$invalid' 验证 Prop

javascript - 在另一个 Controller 中使用来自一个 Controller 的数据

javascript - AngularJs 和套接字服务器

javascript - 插入数组控制台日志可以看到但不会在 html 中呈现,为什么? Angular JS

javascript - 限制 AngularJS 中的 $scope

AngularJS 数据绑定(bind)类型

angularjs - 使用指令在预览模板和编辑模板之间切换

javascript - $watch 没有被解雇