javascript - 我想将 html id 绑定(bind)到指令中

标签 javascript html angularjs

我正在努力学习 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/

相关文章:

angularjs - AngularJs 中选择下拉列表的第一个选项为空

javascript - 如何从异步调用返回响应?

javascript - 有没有办法在 HTML5 中播放 mpeg 视频?

javascript - 使用 javascript 或 jquery 从选择下拉列表中删除重复项

html - 通过html select标签创建时如何获取UIPickerView的对象引用

javascript - 使用 ngClass 更改部分 CSS 类

angularjs - 如何编写 karma/jasmine 集成测试,将值按顺序传递到下一个测试?

javascript - JS/Nodejs 无法访问对象的引用索引

javascript - IE9 中 jquery 中的每个循环中的“未定义”

javascript - Vue 路由器链接仅在刷新后工作