0

私はAngularJSを初めて使い、親スコープの値をバインディングのないディレクティブスコープ(2つの別々のインスタンス)にコピーする方法を知りました。私のnewHostTemplateは{{newHost.ipAddress}}を呼び出して実装されていますが、newHostはディレクティブのスコープであり、親ではありません。親スコープからディレクティブスコープへの値のコピー

host.directive('newHost', function(){ 
    return { 
     restrict: 'E', 
     template: '<div ng-include="getTemplateUrl()"></div>', 
     scope: true, 
     link: function(scope, element, attr) { 
      scope.newBox = function() { 
       scope.getTemplateUrl = function() { 
        return 'hosts/newHostTemplate.html'; 
       } 
      } 
     } 
    } 
}); 

host.controller('hostsController', function($scope, $http, $window, $rootScope){ 
    $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) { 
     console.log("failed to change routes"); 
    }); 

    $scope.newHost = {}; 
    $scope.addNewHost = function() { 
     $http({ 
      method : 'POST', 
      url  : 'http://192.168.0.99:5000/newHost', 
      data : JSON.stringify($scope.newHost), // pass in data as strings 
     }) 
     .success(function(data) { 
      console.log(data); 
      $scope.newBox() 
      $scope.newHost = {} 
      //on success we want to close the modal and reset the data 
      $scope.dismiss() 
     }); 
    }; 
}); 

現在、私がこれを実行すると、newBoxが関数ではないというエラーが表示されます。

答えて

2

スコープを分離する必要があります。 の代わりにスコープ:true、do スコープ:{}

ディレクティブと、親からの任意の明示的な入力は、定義されたスコープ変数を介して次のようになります。

scope: { 
    twoWayBoundInputOne: '=', 
    staticStringInputTwo: '@', 
    functionThree: '&' 
} 

また、アーキテクチャは、このようなサービスへのAJAXリクエストとして、再利用可能なコードを置くことですお勧めします。 https://docs.angularjs.org/guide/services

$ scopeまたは$ httpと同じ方法で、ディレクティブとコントローラにサービスを注入します。

あなたのサービスは次のようになります。

/* global bz_app */ 
host.factory('hostsService', ['$http', 
function ($http) { 
    return function() { 
     this.add = function() { 
      return $http({ 
       method : 'POST', 
       url  : 'http://192.168.0.99:5000/newHost', 
       data : JSON.stringify($scope.newHost), // pass in data as strings 
      }); 
     }; 

     this.templateUrl = function() { 
       return 'hosts/newHostTemplate.html'; 
     }; 
    }; 
}]); 

// then in your controller or directive you can do this, to get an instance that doesn't get impacted by other instances. 
scope.host = new HostsService(); 
+0

こんにちはアルテム、上記の範囲は、私のシナリオに適用される – DorkMonstuh

+0

あなたのスコープ入力がスコープになりますか:{ホスト:「=」}、あなたがスコープに渡します.new-hostから

+0

テンプレートを使用する代わりに静的テンプレートURLのテンプレートをng-includeにしているのはなぜですか: '' hosts/newHostTemplate.html '' ?これにより、ng-includeによって作成される追加のスコープが作成されなくなります。テンプレートは、ディレクティブのスコープ内に直接存在します。 –

関連する問題