当点击(+)增量按钮时,传递给我的指令的第一个{{labelText}}绑定在视图中显示为{{labelText}}。即使我的Chrome检查器中的AngularJS属性显示其值为"输入一个名称来标识每个资源"。随后点击增量按钮显示输入字段会为LabelText附加正确的值。(见下面的截图)
这是我的控制器
.controller(' CounterCtrl',function($ scope){
'use strict';
angular.module('Carrepair2.controllers', ['ionic', 'ui.bootstrap', 'Carrepair2.directives.addinputs', 'Carrepair2.directives.removeinputs'])
$scope.decrement = function() {
$scope.count = $scope.count - 1;
if ($scope.count < 0){
$scope.count = 0;
}
};
$scope.increment = function() {
$scope.count = $scope.count + 1;
};
$scope.labelText = 'Enter a name to identify each resource';
})
这是我的指示
'use strict';
angular.module('Carrepair2.directives.addinputs', ['ionic', 'ui.bootstrap'])
.directive('addinputs', function($compile){
return function(scope, element){
element.bind('click', function(){
var childId = 'space-for-inputs' + scope.$index;
var inputLabelForId = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
angular.element(document.getElementById(childId)).append(
$compile('<div class=\'resource-name-input input_wrapper\'><input type=\'text\' id="' + inputLabelForId + '" required><label for="' + inputLabelForId +'">{{labelText}}</label></div>')(scope));
});
};
});
这是我的模板
<ul class="list">
<li class="item" id="resource{{$index}}" ng-repeat="resource in resources">
<div class="resource-desc">{{resource.description}}</div>
<img ng-src="{{resource.thumb}}">
<div class="incrementer" ng-controller="CounterCtrl">
<button class="count-btn ion-arrow-up-b" ng-click="increment()" ng-init="count=0" addinputs>
<span class="ion-plus-round"></span>
</button>
<div class="count-btn count">{{count}}</div>
<button class="ion-arrow-down-b" ng-click="decrement()" removeinputs>
<span class="ion-minus-round"></span>
</button>
</div>
<div id='space-for-inputs{{$index}}'></div>
</li>
</ul>
抱歉,评论中jsFiddle中的链接不起作用。这是jsFiddle复制问题的链接。 http://jsfiddle.net/KyEr3/106/
答案 0 :(得分:0)
我强烈建议你去阅读如何使用angularjs,我在你的小提琴中看到的很多东西似乎都没有。连续不得不编译不应该是你开始的东西。在任何一种情况下,问题都归结为您如何连接元素点击。当事情发生在角度知识之外时,即这一行:
element.bind('click', function(){
你必须让angular知道更新,这样功能就会变成:
element.bind('click', function(){
angular.element(document.getElementById("space-for-inputs")).append(
$compile('<div class=\'resource-name-input input_wrapper\'><input type=\'text\' id=\'myinput\' required><label for=\'myinput\'>{{labelText}}</label></div>')(scope));
scope.$apply();
});
但是,你应该使用ng-click。以下是您更新后的工作:http://jsfiddle.net/5ThTT/