2016-05-19 51 views
0

我嘗試在一個角度指令內創建一個函數,該函數應該只更改一個對象值。更改指令中函數參數的對象值

它不會直接傳遞變量的函數工作:

<body ng-controller="MainCtrl"> 
    <div test ng-click="changeVar(variable.value)">{{ variable.value }}</div> 
</body> 

app.directive('test', [function(){ 
    return { 
     link: function(scope, elem, attrs) { 
      scope.variable = { 
      value : "bla" 
      }; 
      scope.changeVar = function(value) { 
      value = "hhuhu" 
      }; 
     } 
    } 
}]); 

但傳遞父對象不:

<body ng-controller="MainCtrl"> 
    <div test ng-click="changeObj(variable)">{{ variable.value }}</div> 
</body> 


app.directive('test', [function(){ 
    return { 
     link: function(scope, elem, attrs) { 
      scope.variable = { 
      value : "bla" 
      }; 
      scope.changeObj = function(obj) { 
      obj.value = "hhuhu" 
      }; 
     } 
    } 
}]); 

爲什麼我必須通過父對象的函數覆蓋該值,並且不能直接通過該值來覆蓋它?我錯過了什麼嗎?

+1

這就是javascript的工作原理。檢查例如這個問題:http://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference – apieceofbart

回答

3

我想你在這裏失去的是在angularjs中的範圍的概念以及它們是如何傳遞的。

當你宣佈你的指令是這樣的:

app.directive('parent', [function(){ 
    return { 
     controller: function($scope) { 
     $scope.variable = {}; 
     // init 
     $scope.variable.value = "foo"; 

     } 
    } 
}]); 


app.directive('child', [function(){ 
    return { 
     controller: function($scope) { 

      // here you are directly using the parent's scope 
      // so you can access $scope.variable directly 
      // without sending it in the function 
      $scope.changeObj = function(replacement) { 
      $scope.variable.value = replacement ; 
      }; 
     } 
    } 
}]); 

你基本上是告訴角度使用父範圍的範圍,因爲你沒有定義你的指令,一個特殊的範圍。

(順便說一句,這種操作:

 scope.changeObj = function(obj) { 
     obj.value = "hhuhu" 
     }; 

不應該在鏈接功能,但在控制器,它看起來像控制器邏輯對我說:)

的第二件事,你可以做通過參數傳遞給孩子送範圍變量,如下所示:

app.directive('parent', [function(){ 
    return { 
     controller: function($scope) { 
     $scope.variable = {}; 
     // init 
     $scope.variable.value = "foo"; 

     } 
    } 
}]); 


app.directive('child', [function(){ 
    return { 
     scope:{myVariable: '='}, 
     controller: function($scope) { 

      // here you are directly using the child's scope 
      // but since you have defined double binding, 
      // changing this in the child will also update the parent 
      $scope.changeObj = function(replacement) { 
      $scope.myVariable.value = replacement ; 
      }; 
     } 
    } 
}]); 


<body ng-controller="MainCtrl"> 
    <div test my-variable="variable" ng-click="changeObj('some text')">{{ variable.value }}</div> 
</body> 

我希望這是明確的,現在

+0

好吧,我現在得到它非常感謝你的時間! – user3301565