Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangularjs-controlleras

Have a dynamic html element using AngularJS Directive WHITOUT $scope?


I want to use This Plunker sample code to add some elements dynamically to HTML page using AngularJS. (You should run It in a new link, not in editor environment) This is my first experience in declaring AngularJS Directive (except for simple tests). I have two questions about this sample:

  1. My approach is using Controller as instead of $Scope in my controllers. (I don't know the name of this approach!) So what should I do with the sample code above? since it uses $compile(...)($scope). which changes should be applied?
  2. Is the Scope in Directive related to controller? So, If I could omit the scope from controller in this case, should I apply any changes to directive?

Solution

  • 1) When use contrller as syntax so for $compile(...)($scope) change to $compile(...)(vm). and also for all function and variable instead of $scope use vm or this

    var vm = this;
    

    so instead of $scope.list use vm.list and for function also use.

      $scope.do = function() ..
    
      vm.do = function() ....
    

    2) In directive add controllerAs like to this

      app.directive('myDirective', function () {
       return {
       scope: {},
       controller: function () {
         this.name = 'Elnaz'
       },
       controllerAs: 'ctrl',
       template: '<div>{{ctrl.name}}</div>'
      };
    });
    

    and if you want to refer to external controller use this

       app.directive('myDirective', function () {
         return {
         restrict: 'A',
         controller: 'EmployeeController',
         controllerAs: 'ctrl',
         template: ''
        };
     });
    

    in your view change like to this:

      <div ng-controller="myController as ctrl">
         {{ctrl.name}}
    
         <button type="button" ng-click="ctrl.do()">Do</button>
      </div>
    

    Edit: works demo