AngularJS + style is not applied to field - javascript

I am trying to apply a color to a message on an api response.
example:
angularJS:
.then(function (response) {
angular.element(document.getElementById("msg")).css('color', '#00662f');
$scope.Messages = response.data;
and my HTML:
<div id="msg" ng-repeat="msg in Messages">{{msg}}</div>
but this line:
angular.element(document.getElementById("msg")).css('color', '#00662f');
does not seem to be applied to the color of the message.
Can you tell what I am doing wrong?
Thank you for your help.
Erasmo
UPDATE - My Solution
added a boolean
$scope.IsColor == true;
Set it to false/true based on the API response:
if (response.data.indexOf("sucessfully added") !== -1) {
$scope.Messages = response.data;
$scope.IsColor = true;
angular.element("#msg").focus()
return true;
}
else {
$scope.Messages = response.data;
$scope.IsColor = false;
angular.element("#msg").focus()
return false;
}
Then in the HTML
<div id="msg" ng-repeat="msg in Messages" ng-class="$scope.IsColor ? 'text-green' : 'text-red'">{{msg}}</div>

You should do it via ng-class or ng-style. Please see stackblitz for how to update style:
https://stackblitz.com/edit/angularjs-puf49l
Beside the style, in your HTML:
<div id="msg" ng-repeat="msg in Messages">{{msg}}</div>
You should replace id with class, using id's to identify elements is often considered a bit bad, because id's are global and it would instantly mess up if I happen to have a collision.

Try this
angular.element(document.querySelector("msg")).css('color', '#00662f');

Related

add-from-autocomplete-only = "false" with auto-complete in ngInputTag Control not working

After spending a lot of time in investigating to resolve the issue to allow any tag along with autocomplete feature in ngInputTag. I end up with no results.
The issue is when I type the text which is in autocomplete list the tags get added successfully but when point comes to add the tags which is not in the tag list it accepting the first tag but when I enter second tag which is not in autocomplete list it makes the text color Red and not accepting the tag input.
To resolve the issue I have used on-tag-added but it did not worked. Same issue has been reported on Git-Hub Issue Link
Below is my code:
HTML
<tags-input ng-model="model" display-property="Name" key-property="Key"
placeholder="Enter Tags" add-from-autocomplete-only="false"
allow-leftover-text="true">
<auto-complete source="loadTags($query)"
highlight-matched-text="true"
select-first-match="true">
</auto-complete>
</tags-input>
Controller JS Code:
$scope.model = [];
$scope.loadTags = function (query) {
var deferred = $q.defer();
$http.get(ApiUrls.GetTagsByQuery + (query != null ? ("?query=" + query) : ""))
.then(function (result) {
if (result.data == null) {
result = [];
}
deferred.resolve(result.data);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
};
Any Help will be Highly Appreciated. Thanks.
Same problem !!! But if you remove key-property then it will works.
key-property is only for duplicate issue

Set flash message after redirect in angularjs

I am just starting with Angular js. I have a doubt in that. I want to set flash messsage after redirect.
In my case, I have a form and am saving the data through http requst. In the success function I put window.location(). It is another page. I want to set a flash message in that page.
js
$scope.Save_Details = function (id)
{
$http.post(base_url+"sur/sur/save_data/"+id,{data:$scope.Surdata}).
success(function(response) {
// $scope.successTextAlert = "Saved";
// $scope.showSuccessAlert = true;
window.location = "#/surpage/nextpage?show_message= true";
});
}
new update
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
alert(messageFlag);
$scope.successTextAlert = "Saved";
$scope.showSuccessAlertMsg = true;
}
view
<div class="alert alert-success" ng-show="showSuccessAlert">
<button type="button" class="close" data-ng-click="switchBool('showSuccessAlert')">×</button> <strong> {{successTextAlert}}</strong>
</div>
Anyone help me?
Put this code in HTML -
<!-- message text -->
<div class=" panel-{{alerts.class}}" ng-show="alerts.messages" >
<div ng-repeat="alert in alerts.messages track by $index" class="panel-body alert-{{alerts.class}}" >{{alert}}</div>
</div>
Put this code in angular model -
$rootScope.alert = function(type,msg){
$rootScope.message.push(msg);
$rootScope.alerts = {
class: type,
messages:$rootScope.message
}
}
For success message -
$rootScope.alert('success',"Success !!!");
For Error message -
$rootScope.alert('danger',"Error.");
You can use toastr JS specially for flash.
http://codeseven.github.io/toastr/demo.html
By using below js code, you can display a flash message.
For success message :
toastr"success";
For Error message :
toastr"success";
EDIT - Adding code
yourAppModule.controller('nextPageController', function($location){
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
//show your message
}
});
When you navigate to "nextpage" pass a flag along -> #/surpage/nextpage?show_message= true
In the "nextpage" controller, read the query string value for
"show_message" ( inject $location to your controller and get value
using $location.search().show_message)
if that value == true, show your flash message

Return content for it to be shown - Right now nothing comes out

When I have picked my json from my controller, so when I have to write it in index.cshtml side so but when I type "module." then there's nothing up around img, text or ID, etc.
by my ng-repeat will it count as I want appears as it should.
The problem here just in that it will not enter text and img whether it is empty or not. both my questions that appear on the page has no image but right now the picture is shown on the page.
It gives me such a helping hand to know what to write about it must be img or text or otherwise.
Opgaver.html
<input type="hidden" ng-init="Id='2'" ng-model="Id" />
<div ng-repeat="module in Newslist" style="clear:both; margin:7px 0; min-height:110px; margin:5px 0;">
<div class="col-md-8">
<p>{{module.text}}</p>
</div>
<div class="col-md-3" ng-show="module.Img != null">
<img class="img-responsive img-rounded mb-lg" src="img/projects/project.jpg">
</div>
</div>
Opgaver.js
var app = angular.module('Opgaver', []);
app.controller('OpgaverCheck', function ($scope, $http) {
//GET
$scope.$watch("Id", function() {
var url = "/opgaver/kategori/" + $scope.Id;
$http.get(url).success( function(response) {
$scope.Newslist = response;
});
});
});
Controller:
[HttpGet]
public JsonResult kategori(int Id)
{
var db = Helpers.HelperToTables.DbValue;
List<ListOpgave> list = db.LektionerOpgaves.Where(i => i.fk_LektionerId == Id).OrderByDescending(i => i.id).Select(x => new ListOpgave
{
Id = x.id,
Img = x.LektionerOpgaveImg.value,
Text = x.text,
}).ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
First, you have "module.text", but in your MVC Controller, you have "Text". They must be exactly the same including case. Try changing "module.text" to "module.Text". Also, make sure your Json is actually returning a list by putting breakpoints in both controllers.
I think you want $scope.Newslist = response.data;
The response object has five properties and the information you want is contained in one of them. So as you have it written, Newslist is equal to the entire response, including the status and headers, rather than just the response data.
See the documentation on $http.

ngClass style with variable in key

I hope someone can help me out.
I am using angular v1.3.14 and I try to add a scope variable in a key of a ng-class map.
example
<b class="fixedClass" ng-class="{'classOne' : x === 'foo',
'classTwo-%(y)%' : x === 'bar'}">
%(z)%
</b>
is there any way to do something like this or is there a way around ?
You can do something like this
angular.module('App',[])
.controller('AppController',['$scope',function($scope){
$scope.y = 10;
$scope.val = 'bar';
var fixedClass = "fixedClass ";
$scope.getCSSClass = function(){
if($scope.val === 'foo'){
return fixedClass + 'classOne';
} else {
return fixedClass + 'classTwo-(' +$scope.y+ ')';
}
};
}])
In Html
<body ng-controller="AppController">
<b ng-class="getCSSClass()">hello</b>
</body>
Here is the working code
Looking at your requirement, it appears you are mixing static class names with dynamic class names. Preferred approach would be
ng-class="['fixedClass',' fixedClass2',getDynamicStyle()]"
getDynamicStyle is exposed in scope to return the value of dynamic class name. You may add any number of dynamic styles.

Update unrelated field when clicking Angular checkbox

I have a list of checkboxes for people, and I need to trigger an event that will display information about each person selected in another area of the view. I am getting the event to run in my controller and updating the array of staff information. However, the view is not updated with this information. I think this is probably some kind of scope issue, but cannot find anything that works. I have tried adding a $watch, my code seems to think that is already running. I have also tried adding a directive, but nothing in there seems to make this work any better. I am very, very new to Angular and do not know where to look for help on this.
My view includes the following:
<div data-ng-controller="staffController as staffCtrl" id="providerList" class="scrollDiv">
<fieldset>
<p data-ng-repeat="person in staffCtrl.persons">
<input type="checkbox" name="selectedPersons" value="{{ physician.StaffNumber }}" data-ng-model="person.isSelected"
data-ng-checked="isSelected(person.StaffNumber)" data-ng-change="staffCtrl.toggleSelection(person.StaffNumber)" />
{{ person.LastName }}, {{ person.FirstName }}<br />
</p>
</fieldset>
</div>
<div data-ng-controller="staffController as staffCtrl">
# of items: <span data-ng-bind="staffCtrl.infoList.length"></span>
<ul>
<li data-ng-repeat="info in staffCtrl.infoList">
<span data-ng-bind="info.staffInfoItem1"></span>
</li>
</ul>
</div>
My controller includes the following:
function getStaffInfo(staffId, date) {
staffService.getStaffInfoById(staffId)
.then(success)
.catch(failed);
function success(data) {
if (!self.infoList.length > 0) {
self.infoList = [];
}
var staffItems = { staffId: staffNumber, info: data };
self.infoList.push(staffItems);
}
function failed(err) {
self.errorMessage = err;
}
}
self.toggleSelection = function toggleSelection(staffId) {
var idx = self.selectedStaff.indexOf(staffId);
// is currently selected
if (idx >= 0) {
self.selectedStaff.splice(idx, 1);
removeInfoForStaff(staffId);
} else {
self.selectedStaff.push(staffId);
getStaffInfo(staffId);
}
};
Thanks in advance!!
In the code you posted, there are two main problems. One in the template, and one in the controller logic.
Your template is the following :
<div data-ng-controller="staffController as staffCtrl" id="providerList" class="scrollDiv">
<!-- ngRepeat where you select the persons -->
</div>
<div data-ng-controller="staffController as staffCtrl">
<!-- ngRepeat where you show persons info -->
</div>
Here, you declared twice the controller, therefore, you have two instances of it. When you select the persons, you are storing the info in the data structures of the first instance. But the part of the view that displays the infos is working with other instances of the data structures, that are undefined or empty. The controller should be declared on a parent element of the two divs.
The second mistake is the following :
if (!self.infoList.length > 0) {
self.infoList = [];
}
You probably meant :
if (!self.infoList) {
self.infoList = [];
}
which could be rewrited as :
self.infoList = self.infoList || [];

Categories