相关疑难解决方法(0)

在AngularJS中添加指令中的指令

我正在尝试构建一个指令,负责声明它的元素添加更多指令.例如,我想构建一个负责添加的指令datepicker,datepicker-languageng-required="true".

如果我尝试添加这些属性然后使用$compile我显然会生成一个无限循环,所以我正在检查我是否已经添加了所需的属性:

angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        element.attr('datepicker', 'someValue');
        element.attr('datepicker-language', 'en');
        // some more
        $compile(element)(scope);
      }
    };
  });
Run Code Online (Sandbox Code Playgroud)

当然,如果我没有$compile元素,那么将设​​置属性但是指令不会被引导.

这种方法是正确的还是我做错了?有没有更好的方法来实现相同的行为?

UDPATE:鉴于这$compile是实现这一目标的唯一方法,有没有办法跳过第一个编译传递(该元素可能包含几个子节点)?也许通过设置terminal:true

更新2:我已经尝试将指令放入一个select元素中,正如预期的那样,编译运行两次,这意味着预期option的数量是预期的两倍.

javascript model-view-controller mvvm angularjs angularjs-directive

197
推荐指数
3
解决办法
10万
查看次数

Angular指令如何向元素添加属性?

我想知道这个片段的工作方式是什么:

//html
<div ng-app="app">
    <div ng-controller="AppCtrl">
        <a my-dir ng-repeat="user in users">{{user.name}}</a>
    </div>
</div>

//js
var app = angular.module('app', []);
app.controller("AppCtrl", function ($scope) {
    $scope.users = [{name:'John',id:1},{name:'anonymous'}];
    $scope.fxn = function() {
        alert('It works');
    };

})  
app.directive("myDir", function ($compile) {
    return {
        link:function(scope,el){
            el.attr('ng-click','fxn()');
            //$compile(el)(scope); with this the script go mad 
        }
     };
});
Run Code Online (Sandbox Code Playgroud)

我知道这是关于编译阶段的,但我不明白这一点,所以简短的解释会非常感激.

angularjs angularjs-directive

53
推荐指数
1
解决办法
11万
查看次数