3

Plunker link : http://plnkr.co/edit/j7BeL72lwHISCIlwuAez?p=preview

In the above link I am using $scope to pass data. But I want to use the model approach and replace $scope.data in MainController to 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) {}
])

1 Answer 1

2

You can read more about the 'Controller as syntax' here: http://toddmotto.com/digging-into-angulars-controller-as-syntax/

Please note this syntax was introduced in angular 1.2. Your plunkr was using angular 1.0.x.

Here is example plunkr: http://plnkr.co/edit/5ddLyuRlyCt4PqulpOJG

The markup has been modified like this:

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

The controller has been modified like this:

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

Let me know if still encounters problems

Sign up to request clarification or add additional context in comments.

3 Comments

@apairet, Could you tell me what are the advantages of this approach?
@akn, In my case I want to use this.data to have more control over the object(making it public/private) etc. Objects put in $scope are global.
One of the main advantage of the controllerAs syntax is when you have several controllers defined on the same view. Since all of them are named, you access 'scope' variable through {{ctrl.var}} and not {{var}}. You always know the controller you refer to when accessing a variable on the scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.