自定义指令模板中的AngularJS控制变量

AngularJS control variable in custom directive template

本文关键字:AngularJS 控制变量 指令 自定义      更新时间:2023-09-26

我制作了一个自定义指令,在模板中有一个变量ng model="test",

在指令控制器中,如何更改变量?

angular.module("myDirective", []).directive("ngTest", function(){
    return {
      restrict: "E",
      scope: true,
      template: "<input type='text' ng-model='test'>+
      <button ng-click='change()'></button>",
      controller: function ($scope, $element){
        $scope.change = function(){
          // no idea about how to control variable test here.
          $scope.test = "123123123"; //this doesn't work. :(
        }
      } 
    }
  });

这里是为您工作的plunker:)

app.directive("ngTest", function(){
    return {
      restrict: "E",
      scope: true,
      template: "<input type='text' ng-model='test'><button ng-click='change()'>Click Me</button>",
      controller: function ($scope, $element){
        $scope.change = function(){
          // no idea about how to control variable test here.
          $scope.test = "123123123"; //this doesn't work. :(
        }
      } 
    }
  });

我发现的问题是指令中的"+"不起作用——你需要在同一行中提供完整的tempalte,或者使用tempalteUrl为其提供值。