Javascript 如何将值直接传递到指令中?
我有一个简单的角度指令,我想把值传递给它Javascript 如何将值直接传递到指令中?,javascript,angularjs,Javascript,Angularjs,我有一个简单的角度指令,我想把值传递给它 <div my-component binding-foo="foo"> <strong>get:</strong> {{isolatedBindingFoo}} // get it to output foo? </div> 获取:{{isolatedBindingFoo}}//将其获取到输出foo? HTML 干杯AngularJS将HTML属性更改为JS属性。例如,HTML中的bind
<div my-component binding-foo="foo">
<strong>get:</strong> {{isolatedBindingFoo}} // get it to output foo?
</div>
获取:{{isolatedBindingFoo}}//将其获取到输出foo?
HTML
干杯AngularJS将HTML属性更改为JS属性。例如,HTML中的
bindingFoo
将被破坏为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'];
}
}
});
但在示例中,这就足够了:
angular.module('myModule', [])
.directive('myComponent', function() {
return {
restrict:'EA',
scope: {
'isolatedBindingFoo': '@bindingFoo'
}
}
});
您能发布指令的代码吗?看起来不错,但我无法让它工作。我仍然对绑定是如何工作的感到困惑。下面是一个示例,您需要从属性中删除
-foo
,只需将其更改为binding='foo'
。这里有一个更新的fiddle.bah,对不起,我对jsfiddle不太熟练…重点是…确保HTML中的绑定与指令中范围属性中的值匹配。在本例中,我将其修改为仅为绑定
,但如果需要,可以在指令中将其定义为“binding foo”
。所以scope:{“binding-foo”:“=binding-foo”},然后在链接函数中将其引用为attrs['binding-foo']`
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'];
}
}
});
angular.module('myModule', [])
.directive('myComponent', function() {
return {
restrict:'EA',
scope: {
'isolatedBindingFoo': '@bindingFoo'
}
}
});