我希望将指令中的属性中的多个值公开给$ scope。 指令是动态生成的,如下例所示:
<my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>
我需要$ scope中的值来将它们提供给模板并使用它们。
答案 0 :(得分:5)
容易......: - )
var app = angular.module('app', []);
app.controller('myCtrl', function ($scope) {});
app.directive('myDirective', function() {
return {
restrict: 'E',
template: '<p>myDirective:</p>{{firstValue}}, {{secondValue}}, {{thirdValue}}',
scope: {
firstValue: '@',
secondValue: '@',
thirdValue: '@'
},
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myCtrl">
<my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>
</div>
</div>
&#13;
但你真的应该尝试自己编写这种代码,下次......: - )
答案 1 :(得分:1)
var app = angular.module('app', []);
app.controller('homeCtrl', function ($scope) {
});
app.directive('myDirective', function() {
return {
restrict: 'AE',
template: '<h3>My Directive</h3><p>{{firstValue}}|{{secondValue}}|{{thirdValue}}</p>',
scope: {
firstValue: '@',
secondValue: '@',
thirdValue: '@'
},
link: function(scope, element, attr) {
console.log(scope.firstValue)
console.log(scope.secondValue)
console.log(scope.thirdValue)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive>
</div>
</div>