我有一个简单的指令,应该用字符串代替一个数字,但它一直显示数字。
// CS compiled
app.directive('stock', [
'$interpolate', function($interpolate) {
return {
restrict: 'C',
link: function(scope, element) {
var display, html;
html = $interpolate(element.html())(scope);
display = (function() {
switch (html) {
case '0':
return 'Out of stock';
case '1':
return 'Available';
case '2':
return 'Available 3-5 days';
case '3':
return 'Available 2 weeks';
case '4':
return 'Available 2 months';
default:
return '';
}
})();
return element.html(display);
}
};
}
]);调试时,我看到内容正在被替换。


小提琴
发布于 2013-07-26 16:37:02
首先,您需要将0作为字符串传递。您应该使用范围并获得状态,这将更容易。小提琴。
tpl:
<div ng-app="myApp">
<label class="stock" status="status"></label>
</div>联署材料:
// CS compiled
app = angular.module('myApp', [])
app.run(function ($rootScope) {
$rootScope.status = '0'; //pass as string since you filter on string in the case statement
})
app.directive('stock', [
'$interpolate', function ($interpolate) {
return {
restrict: 'C',
scope: {
status: '=status'
},
link: function (scope, element) {
var display, html;
html = $interpolate(element.html())(scope);
display = (function () {
switch (scope.status) {
case '0':
return 'Out of stock';
case '1':
return 'Available';
case '2':
return 'Available 3-5 days';
case '3':
return 'Available 2 weeks';
case '4':
return 'Available 2 months';
default:
return '';
}
})();
return element.html(display);
}
};
}]);发布于 2013-07-26 17:44:42
问题是您在元素中使用了{{...}},因此manual负责更新元素的内容,您对innerHTML的手动更改实际上被框架覆盖。另外,您的实现是使用HTML文本作为共享数据的媒介,这不是处理数据的角度。
sza的回答已经解决了这个问题,它非常有效;但是,从您的问题中我看到您不想为这个指令创建新的作用域,那么指令的作用域是$rootScope,您可以通过在链接函数中使用scope.status完全访问status。
HTML:
<div ng-app="myApp">
<label class="stock"></label>
</div>联署材料:
app.directive('stock', function () {
return {
restrict: 'C',
link: function (scope, element) {
var display = (function () {
switch (scope.status) {
case 0:
return 'Out of stock';
case 1:
return 'Available';
case 2:
return 'Available 3-5 days';
case 3:
return 'Available 2 weeks';
case 4:
return 'Available 2 months';
default:
return '';
}
})();
element.html(display);
}
};
});http://jsfiddle.net/6Vyz9/1/
此外,
如果希望标签在status更改时自行更新,则可以在链接函数中使用$watch。
联署材料:
app.directive('stock', function () {
return {
restrict: 'C',
link: function (scope, element) {
scope.$watch('status', function () {
var display = (function () {
switch (scope.status) {
case 0:
return 'Out of stock';
case 1:
return 'Available';
case 2:
return 'Available 3-5 days';
case 3:
return 'Available 2 weeks';
case 4:
return 'Available 2 months';
default:
return '';
}
})();
element.html(display);
});
}
};
});http://jsfiddle.net/6Vyz9/2/
https://stackoverflow.com/questions/17886188
复制相似问题