簡體   English   中英

是否有使用AngularJS指令WHITOUT $ scope的動態html元素?

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

我想使用This Plunker示例代碼使用AngularJS將一些元素動態添加到HTML頁面。 您應該在新的鏈接中運行它,而不是在編輯器環境中運行 )這是我在聲明AngularJS指令時的第一次經驗(簡單測試除外)。 關於此示例,我有兩個問題:

  1. 我的方法是在Controller as中使用Controller as而不是$Scope (我不知道這種方法的名稱!)那么我應該如何使用上面的示例代碼? 因為它使用$compile(...)($scope) 應該應用哪些更改?
  2. 指令中的范圍是否與控制器有關? 因此,如果在這種情況下可以忽略控制器的作用域,是否應該對指令應用任何更改?

1)當使用contrller作為語法時,對於$compile(...)($scope)更改為$compile(...)(vm) 並且對於所有函數和變量,而不是$ scope使用vmthis

var vm = this;

所以不是$scope.list使用vm.list和功能也可以使用。

  $scope.do = function() ..

  vm.do = function() ....

2)在指令中添加controllerAs像這樣

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

如果要引用外部控制器,請使用此

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

在您看來,更改如下:

  <div ng-controller="myController as ctrl">
     {{ctrl.name}}

     <button type="button" ng-click="ctrl.do()">Do</button>
  </div>

編輯: 作品演示

回答您的第一點:

  1. 在控制器內部,您將創建一個變量來表示“ controller as”;

    var vm = this;

  2. 現在綁定到$ scope的所有屬性現在將成為vm的一部分

  3. 在HTML中:用div綁定控制器的方法: <div ng-controller="customCntrl as vm"
  4. 現在,在視圖中,而不是直接引用作用域屬性,您將必須在vm之前添加前綴,如下所示:vm.name
  5. 在指令中:將控制器與“ controller as”綁定的方式:

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

      } }); 

對第二點的回答:

  1. 您仍然可以像這樣應用廣播並通過'vm'發出:

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

    並捕獲它:$ scope。$ on('topic-123',function(event,msg){});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM