我有一个指令调用模板。在模板中,我使用了ng-class,它在点击时添加了一个类。但是,点击时,这个类不会被添加。ng-class不能使用templateURL的自定义指令
指令:
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
data: "="
},
templateUrl: 'home/user.html'
}
}
);
家/ user.html
<label for="firstname">First Name</label>
<input type="text" ng-model="data.input[0].value" required ng-class="{true : 'necessary'}[errorFirstName]" id="firstname">
的index.html:
<div ng-controller="MyController">
<my-directive data="myData"></my-directive>
<button ng-click="checkUsr()">Check user</button>
</div>
MyController.js
app.controller('MyController', function($scope) {
$scope.checkUsr = function() {
$scope.errorFirstName = true;
}
});
UPDATE:
我试过compilign太:
app.directive('myDirective', function ($compile) {
return {
restrict: 'E',
scope: {
data: "="
},
templateUrl: 'home/user.html',
link: function(scope, element, attrs) {
$compile(element.contents())(scope);
}
}
}
);
尝试范围:{data:“= data”} –
This this .. ng-class =“{neccessary:errorFirstName}” – adamjld
您没有在MyController中定义myData,并且您试图将它作为数据参数传递给你的指令。试着在MyController中初始化一个myData对象:'$ scope.myData = {errorFirstName:false};'然后稍微改变你的checkUsr函数:'$ scope.myData.errorFirstName = true;' –