0

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?
4

2 回答 2

0

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

于 2016-05-18T06:09:06.350 回答
0

Answer for your 1st point:

  1. Inside your controller, you would have create one variable which would represent "controller as";

    var vm = this;

  2. Now all the properties which was binded to $scope will now be the part of vm

  3. In HTML: way to bind controller with div : <div ng-controller="customCntrl as vm"
  4. Now in the view instead of refering scope properties directly, you will have to prefix vm before that like this: vm.name
  5. In the directive: Way to bind controller with "controller as":

    app.directive('customDir', function() { return { controller: 'customCntrl', controllerAs: 'vm', ...

                }
            }); 
    

Answer to your 2nd point:

  1. You can still apply broadcast and emit over 'vm' like this:

    $scope.$watch('vm.name', function() { $scope.$broadcast('topic-123', 'msg'); });

    And to capture it: $scope.$on('topic-123', function(event, msg) {});

于 2016-05-18T06:33:53.103 回答