我正在努力学习 AngularJS 和 JavaScript 并更好地理解它们,所以请多多包涵。
我有一个指令,我想与 index.html 中的 div 的 ID 绑定(bind),现在我已经将 $scope.name 硬编码到 Controller 中。 我想知道是否有人能指出我正确的方向。
此外,由于我可能会制定多个指令,我能否将 Controller 移到指令之外,而不是为所有指令重复自己?
我的指令.js
angular.module('myModule.directive', []).
directive('myDirective', [function() {
return {
restrict: 'A',
replace: true,
scope: true,
controller: ['$scope', function ($scope) {
$scope.name = 'John Smith';
}],
link: function (scope, elem, attrs) {
},
templateUrl: 'partials/box.html'
};
}])
index.html:
<div>Information
<div id="name1" my-directive></div>
<div id="name2" my-directive></div>
<div id="name3" my-directive></div>
</div>
部分:
<div class="box-for-person">
<!-- I want to use the html id here-->
<div class="name-text">{{ name }}</div>
</div>
如有任何帮助,我们将不胜感激。
最佳答案
使用isolated scope :
JavaScript
angular.module('myModule.directive', []).
directive('myDirective', [function() {
return {
restrict: 'A',
replace: true,
scope: {
name: '='
},
template: '<div>{{name}}</div>'
};
}]);
function MyCtrl($scope) {
$scope.foo = 'Jorge';
}
HTML
<div my-directive data-name="foo"></div>
关于javascript - 我想将 html id 绑定(bind)到指令中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22047643/