bradley546994 bradley546994 - 13 days ago 6
AngularJS Question

Angular find via attribute

I have problem with my script.

js

$scope.showConfirm = function(e) {
var confirmPopup = $ionicPopup.confirm({
title: 'some title',
template: 'ccccccc'
});
confirmPopup.then(function(res) {
if(res) {
var a = angular.element(document.querySelectorAll("div['data-id'="+e+"]"));
console.log(a);
}
});
};


and html:

<div class="green" data-id="{{mydiv.mydiv_id}}">
<p>some text </p>

<button class="button button-primary" ng-click="showConfirm({{mydiv.mydiv_id}})">
Wykonane
</button>
</div>


Everything works well, id is allocated and when I check the console that also is all okay, but at this stage need to click the button changed class.For example when I'm click "showConfirm()" I need change class in div where data-id = showConfirm(id).
Now my div have class green, when I' click button this class change to red. In jquery the same script view like this:

$(button).on(click, function(e){
var element = $("div[data-id="+e+"]");
element.removeClass(green);
element.addClass(red)
});


How to do it?

EDIT:

I see that I need to add full code to make it clear :)

updated code:

$scope.showConfirm = function(e) {
var confirmPopup = $ionicPopup.confirm({
title: 'title',
template: 'eeeeee'
});
confirmPopup.then(function(res) {
if(res) {
var a = angular.element(document.querySelectorAll("div['data-id'="+e+"]"));
console.log(a);
$http.get("http://example/rest_api/json?id="+e)
.success(function(data){
// if success set green
})
.error(function(){
// if error set red
})
}
});
};


I need change class when my server is success response.

Answer

Consider using ng-class instead of class.
For example

You could also do this using objects, and based on your edit it could be something like:

Updating the HTML

<div data-id="{{mydiv.mydiv_id}}" ng-class="conditions[mydiv.mydiv_id] ? 'green' : 'red'">

And in your controller $scope.conditions = {}; and just set it to true or false in your success and error like : $scope.conditions[e] = true /* or false */;

Note. If you want the default to be green just set the condition to true on init or do the validations and settings assuming the expected to be a negative value.

Comments