【问题标题】:How to pass object from controller to directive without using $scope in angularJS如何在不使用 angularJS 中的 $scope 的情况下将对象从控制器传递到指令
【发布时间】:2014-08-19 20:50:20
【问题描述】:

Plunker 链接: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) {}
])

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您可以在此处阅读有关“作为语法的控制器”的更多信息: 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>
    

    控制器修改如下:

    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'
            }
        ];
    });
    

    如果还有问题请告诉我

    【讨论】:

    • @apairet,你能告诉我这种方法的优点是什么吗?
    • @akn,就我而言,我想使用 this.data 来更好地控制对象(使其成为公共/私有)等。放入 $scope 的对象是全局的。
    • controllerAs 语法的主要优点之一是当您在同一个视图上定义多个控制器时。由于它们都已命名,因此您可以通过 {{ctrl.var}} 而不是 {{var}} 访问“范围”变量。在访问作用域上的变量时,您总是知道您所指的控制器。
    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 2022-11-18
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2017-12-08
    相关资源
    最近更新 更多