2015-05-24 34 views
1

我有一個簡單的角度指令,我想傳遞價值。如何將值直接傳遞給指令?

<div my-component binding-foo="foo"> 
    <strong>get:</strong> {{isolatedBindingFoo}} // get it to output foo? 
</div> 
+0

你能發佈你的指令代碼嗎? –

回答

0

AngularJS軋液機的HTML屬性JS性質。例如,binding-foo在HTML將在JS在一起廝混到bindingFoo,反之亦然

var myModule = angular.module('myModule', []) 
.controller('yourController', ['$scope', function($scope) { 

    $scope.isolatedBindingFoo = ''; 

}]) 
.directive('myComponent', function() { 
    return { 
     restrict:'E,A', 
     controller: 'yourController', 
     scope: true, 
     link: function($scope, $element, attrs) { 
      $scope.isolatedBindingFoo = attrs['bindingFoo']; 
     } 
    } 
}); 

http://jsfiddle.net/b2xo0o5u/3/

但在例如情況下,這已經足夠了:

angular.module('myModule', []) 
.directive('myComponent', function() { 
    return { 
     restrict:'EA', 
     scope: { 
      'isolatedBindingFoo': '@bindingFoo' 
     } 
    } 
}); 

http://jsfiddle.net/b2xo0o5u/4/

1

HTML

<div my-component binding='foo'> ... </div> 

JS

yourApp.controller('yourController', ['$scope', function($scope) { 

    $scope.isolatedBindingFoo = ''; 

}]) 
.directive('myComponent', function() { 
    return { 
     controller: 'yourController', 
     scope: { 
      'binding': '=binding' 
     }, 
     link: function($scope, $element, attrs) { 
      $scope.isolatedBindingFoo = attrs['binding']; 
     } 
    } 
}); 

http://fdietz.github.io/recipes-with-angular-js/directives/passing-configuration-params-using-html-attributes.html

乾杯

+0

這看起來不錯,但我無法讓它工作。而且我仍然對約束如何工作感到困惑。這是[小提琴](http://jsfiddle.net/b2xo0o5u/) –

+0

您需要從您的屬性中刪除'-foo',並將其更改爲'binding ='foo''。這是一個更新的小提琴。 –

+0

https://jsfiddle.net/b2xo0o5u/6/ –