如何将值直接传递给指令?

时间:2015-05-24 22:51:22

标签: javascript angularjs

我有一个简单的角度指令我想将值传递给。

var scoremodels = new List<ScoreModel>
{
    new ScoreModel {Subject = "Subj1", Points = 6},
    new ScoreModel {Subject = "Subj2", Points = 3},
    new ScoreModel {Subject = "Subj3", Points = 8},
}
ViewModel = new ViewSubjectGradeViewModel(scoreModels);
this.DataContext = ViewModel;

2 个答案:

答案 0 :(得分: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

干杯

答案 1 :(得分:0)

AngularJS将HTML属性变为JS属性。例如,HTML中的binding-foo将被损坏为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/