簡體   English   中英

使用transclude AngularJS指令打破了$范圍

[英]AngularJS directive using transclude breaks the $scope

我是AngularJS的新手。 我嘗試使用選項transclude=true創建指令,但似乎破壞了$ scope。 這是我的代碼:

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
    <script type="text/javascript">
      var app = angular.module('myApp', []);

      app.controller('myController', ['$scope', function($scope){
        $scope.myText = 'Hello';

        $scope.facility = null;
        $scope.facilities = [
          {id:1, name:'One'},
          {id:2, name:'Two'},
          {id:3, name:'Three'}
        ];

        $scope.query = function(){
          console.log($scope.facility, $scope.myText);
        }
      }]);

      app.directive('ohMy', function(){
        return {
          transclude: true,
          template: function(){
            return '<form novalidate><div ng-transclude></div></form>';
          }
        }
      });

    </script>
  </head>
  <body>
    <div ng-controller="myController">
      <oh-my>
        <input type="text" ng-model="myText"></input>
        <div>{{myText}}</div>
        <select ng-change="query()" ng-model="facility" ng-options="f.name for f in facilities"></select>
      </oh-my>
    </div>
  </body>
</html>

當我更改文本框值(myText)時,該文本框下一個div中的文本顯示了我期望的更新值。 但是當我使用下拉菜單時,瀏覽器的控制台始終顯示默認值,但不是這樣。

當我刪除該指令時,一切正常。

創建指令時我做錯了什么? 有解決的辦法嗎?

-更新-

谷歌搜索了一會兒之后,我發現了這個鏈接: AngularJS可以覆蓋但保留指令的作用域並嘗試理解它,然后我將指令代碼修改如下:

  app.directive('ohMy', function(){
    return {
      transclude: true,
      template: function(){
        return '<form novalidate><div ng-transclude></div></form>';
      },
      link: function(scope, element, attrs, ctrl, transclude) {
        transclude(scope, function(clone) {              
          element.children(0).empty().append(clone);
        });
      }
    }
  });

而且它正在按我現在的預期工作。 但是,還有更好的解決方案嗎?

您可以嘗試從$ parent范圍獲取模型:

      <oh-my>
        <input type="text" ng-model="$parent.myText"></input>
        <div>{{myText}}</div>
        // get model from $parent scope.
        <select ng-change="query()" ng-model="$parent.facility" ng-options="f.name for f in $parent.facilities"></select>
      </oh-my>

鏈接演示: http : //plnkr.co/edit/as7dSEybw7PWB24JlPWp?p=preview

暫無
暫無

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

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