簡體   English   中英

如何將數組或對象作為字符串傳遞給指令,然后在指令內部將其用作變量

[英]How to pass array or object to directive as string and then use it as variable inside directive

我有指令'copyPaste',它將元素值復制到'destination'屬性中指定的元素。

// html code
<div ng-app='app'>
 <div ng-controller="mainController">
 <input type='text' ng-model='firstInput' copy-paste destination='secondInput'>
 <input type='text' ng-model='secondInput'>

 <!-- following does not work -->

   <input type='text' ng-model='param.firstInput' copy-paste destination='param.secondInput'>
 <input type='text' ng-model='param.secondInput'>

 </div>
</div>


//directive code

module.directive('copyPaste',['$rootScope',function($rootScope){
 return {
 restrict:'A',
 link:function(scope,element,attrs,ctrl){
 var destination=attrs.destination;
 scope.$watch(attrs.ngModel, function (v) {
            scope[destination]=v 
            });
 }
 }
}])

//controller

    module.controller('mainController',['$scope',function($scope){
     $scope.firstInput='hello'
    }]);

如果我傳遞簡單變量,則上述代碼有效。 如果我傳遞對象,數組將不起作用。 如何將數組和對象作為字符串傳遞給指令,然后用作變量。 我不想在隔離范圍中運行指令,在隔離范圍中,我需要調用$ scope。$ apply以更新綁定,因此嘗試避免隔離范圍。

JsFiddle

好的,我知道了。 這應該做到-> plunk

基本上遍歷作用域樹以查找要為其設置值的對象。 不是最漂亮,但可以完成工作

var module = angular.module('app', []);
module.directive('copyPaste', ['$rootScope', function($rootScope) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs, ctrl) {
      var destination = attrs.destination;


scope.$watch(attrs.ngModel, function(v) {
        var splitted = destination.split('.');
        if (splitted.length > 1) {
          var value = null;
          var lastKey = "";
          for (var i = 0; i < splitted.length; i++) {
          if(value == null) {
          value = scope[splitted[i]];
          } else {
          if(value[typeof splitted[i] == 'Object']) {
          value = value[splitted[i]];
          } else {
            lastKey = splitted[i];
          }

                    }
          }
          value[lastKey] = v;

                } else {
        scope[destination] = v;
        }
            });
    }
  }
}])

module.controller('mainController', ['$scope', function($scope) {
  $scope.firstInput = 'hello';
  $scope.secondInput = "";
  $scope.param = {};
  $scope.param.secondInput = "";
  $scope.param.firstInput = "Again";
}]);

您可以使用JSON.stringify將值轉換為JSON字符串,然后再使用JSON.parse將JSON文本字符串轉換為Javascript對象

我認為您應該使用事件而不是$ watch,這樣會提高性能。 看看ngChange( https://docs.angularjs.org/api/ng/directive/ngChange


我認為問題可能是由於$ watch無法正確檢查您的變量。

您可以嘗試將objectEquality布爾值設置為true(此處為文檔https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope)

 scope.$watch(attrs.ngModel, function (v) {
                scope[destination]=v 
            }, true); // <-- deep object check

暫無
暫無

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

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