Javascript AngularJS—为什么我无法在指令';s链接功能?
我得到了下面的代码。我希望它会告诉我真实的。然而,它显示了我的错误 有人能给我解释一下,并提供一个解决方案来检查元素中是否存在这个类吗?提前谢谢Javascript AngularJS—为什么我无法在指令';s链接功能?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我得到了下面的代码。我希望它会告诉我真实的。然而,它显示了我的错误 有人能给我解释一下,并提供一个解决方案来检查元素中是否存在这个类吗?提前谢谢 // HTML <tit-txt class="{{editable}}" ng-model="mdEnt.phone"></tit-txt> //JS .directive('titTxt', function () { return { restrict: 'E', scope: {
// HTML
<tit-txt class="{{editable}}" ng-model="mdEnt.phone"></tit-txt>
//JS
.directive('titTxt', function () {
return {
restrict: 'E',
scope: {
ngModel: '=',
},
link: function (scope, element, attrs) {
console.log(element.hasClass('editable'));
},
template: '<input ng-model="ngModel" />',
};
})
//HTML
//JS
.directive('titTxt',函数(){
返回{
限制:'E',
范围:{
ngModel:“=”,
},
链接:函数(范围、元素、属性){
console.log(element.hasClass('editable');
},
模板:“”,
};
})
试着这样做:
// HTML
<div ng-app="myApp" ng-controller="myController">
<tit-txt custom-class="customClass"
cust-var="myVal"></tit-txt>
<div ng-bind="myVal"></div>
</div>
//JS
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.customClass = "editable";
$scope.myVal = "this";
});
app.directive('titTxt', function () {
return {
restrict: 'AE',
replace: true,
scope: {
customClass: '=',
custVar: '='
},
link: function (scope, element, attrs) {
console.log(scope);
console.log((scope.customClass === "editable"));
},
template: '<input class="myClass" ng-Model="custVar"/>',
};
})
//HTML
//JS
var-app=angular.module('myApp',[]);
app.controller('myController',函数($scope){
$scope.customClass=“可编辑”;
$scope.myVal=“this”;
});
应用程序指令('titTxt',函数(){
返回{
限制:“AE”,
替换:正确,
范围:{
customClass:“=”,
custVar:“=”
},
链接:函数(范围、元素、属性){
console.log(范围);
console.log((scope.customClass==“可编辑”);
},
模板:“”,
};
})
编辑:编辑代码以包含工作代码。以下是链接,请尝试以下操作:
link: function (scope, element, attrs, controller) {
console.log(angular.element(element).hasClass('editable'));
}
使用观察程序检测类何时更新:
app.directive('titTxt', function () {
return {
restrict: 'E',
scope: {
myModel: '=',
},
link: function (scope, element, attrs) {
scope.$watch(hasClassEditable, function() {
console.log(element.hasClass('editable'));
});
function hasClassEditable() {
return element.hasClass('editable');
}
},
template: '<input ng-model="myModel" />',
};
})
添加类“可编辑”
editable=“{editable}}”
inputxt=“{inputxt}}”
尝试使用pre功能
link: {
pre: function(scope, element, attr, controllers) {
console.log(element.hasClass('editable'));
},
post: function(scope, element, attr, controllers) {
},
}
如果您使用console.log(元素),它会给您带来什么?我得到false。似乎当我尝试执行
.hasClass('editable')
时。AngularJS还没有在dom中添加可编辑的类。更新了,添加了第四个参数到link(),看看是否有任何变化。我已经尝试了你的解决方案。似乎对我不起作用。我已经编辑了代码。请检查一下,看看这是否适合您!:)谢谢你的回答。我理解你说的插值绑定。但是,这是否意味着如果我使用
,我可以跳过观察者?如果我以ng class
的方式调用该指令,这意味着我没有使用插值绑定,因为我没有使用双花括号。在引擎盖下,该指令使用一个观察者来评估AngularJS表达式并适当地更新元素的类。在计时方面,它将有与插值绑定相同的问题。我可以知道{'editable':true}
是否是插值绑定的一种类型吗?要了解如何避免使用ng class
并直接使用AngularJS表达式计算属性,请参阅。