动态构建模板内部的ng-click不会被触发

时间:2014-11-19 22:17:58

标签: javascript angularjs-directive angularjs-scope angularjs-ng-click angular-template

动态加载的模板中的以下(缩短的)代码中的ng-click不会被触发,而最后一行中的默认模板内的ng-click是!我怎么做才能在不隔离指令范围的情况下解雇它们?

的index.html:

<myone model="mymodel"/>

指令:

angular.module('starter.directives', [])
  .directive('myone', function ($compile, data) {

  // We want to manipulate the DOM so we need a linker function.
  var linker = function(scope, element, attrs) {

    // Wait for the data object to be initialized asynchronously.
    data.initialized.then(function(){
      // This template variable is shortened in this snipped and would normally
      // be build up regarding to the structure of the initialized data object.
      // It further contains a lot of variables from the not isolated scope (e.g.
      // mymodel).
      template =
              '<span class="input-label">{{varInScope}}</span>'
            + '<input type="text" ng-model="' + attrs.model + '" />'
            + '<button ng-click="varInScope = varInScope +1" />';
            // The ng-click above never fires :(

      // compile the expressions and append the new DOM node to this directives element.
      var child = $compile(template)(scope);
      element.append(child);
    };
  };

  return {
      restrict: "E",
      link: linker,

      // need the parent scope instead of a isolated scope because in the template
      // build up above are {{vars}} referenced from it.
      scope: false,

      // Cant use template function instead of the linker function above for
      // dynamically building the template because it's content is unknown and
      // not available on startup (Have to wait for the data object). 
      template: '<div ng-click="thisWorksWhateverIdo()">template</div>'
  };
});

0 个答案:

没有答案