AngularJS - 在模板中注入变量

时间:2015-01-31 14:10:53

标签: javascript angularjs angularjs-directive

这似乎是一个简单的问题,但经过几个月的角度工作后,我仍然在寻找一种干净的方法。

我的模板myTimePicker.html是在一个指令中定义的,所以我得到了

<myTimePicker></myTimePicker>

在我的模板中,我有一个“pickedTime”对象

我需要拾取3次不同的时间,我不想为相同的代码编写3个模板(显然......)。我想将它定义为函数的变量,如:

<myTimePicker ng-***="pickedTime1 as pickedTime" ></myTimePicker>
<myTimePicker ng-***="pickedTime2 as pickedTime" ></myTimePicker>
<myTimePicker ng-***="pickedTime3 as pickedTime" ></myTimePicker>

当你写

时,这在ng-repeat中非常有效
ng-repeat="item in items"

您可以对不同的项目使用相同的模板,但每个项目内部都有不同的变量值。

ng-init不是解决方案,因为在这种情况下:

<myTimePicker ng-init="pickedTime = pickedTime1"></myTimePicker>
<myTimePicker ng-init="pickedTime = pickedTime2"></myTimePicker>
...

pickedTime = pickedTime1 = pickedTime2,他们获得了相同的值pickedTime2

我希望它很清楚,谢谢你的帮助!

2 个答案:

答案 0 :(得分:3)

使用自定义属性并将其与隔离范围结合使用:

<myTimePicker pickedTime="pickedTime1"></myTimePicker>
<myTimePicker pickedTime="pickedTime2"></myTimePicker>
<myTimePicker pickedTime="pickedTime3"></myTimePicker>

scope: {
    pickedTime: '='
}

这样您就可以使用pickedTime属性将控制器范围变量注入指令。


这是一个使用字符串而不是实时的简单示例:

&#13;
&#13;
angular.module('myApp', [])
  .controller('Ctrl', ['$scope',
    function($scope) {
      $scope.pickedTime1 = 'First time';
      $scope.pickedTime2 = 'Second time';
      $scope.pickedTime3 = 'Third time';
    }
  ])
  .directive('myTimePicker', function() {
    return {
      template: '<p>{{pickedTime}}</p>',
      restrict: 'E',
      scope: {
        pickedTime: '='
      }
    }
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl">
  <my-time-picker picked-time="pickedTime1">1</my-time-picker>
  <my-time-picker picked-time="pickedTime2">2</my-time-picker>
  <my-time-picker picked-time="pickedTime3">3</my-time-picker>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<myTimePicker ng-init="pickedTime = pickedTime1"></myTimePicker>
<myTimePicker ng-init="pickedTime = pickedTime2"></myTimePicker>
...

ng-init在上面的代码中不起作用是因为模型pickedTime被修改了两次并且最后设置为pickedTime2

如果您使用<myTimePicker ng-repeat="pickedTime in pickedTimes" ></myTimePicker>,则对于每个myTimePicker元素,ng-repeat将创建一个独立的范围并将新的pickedTime绑定到该范围,可以在您的直接访问