How to store variable in an AngularJS HTML template? - angularjs

How can I store values to variable for example on click in angular? I have the following code which doesn't save the value into variable:
HTML:
<div ng-app='app'>
<a ng-controller="MyController" href="#" ng-click="variable = 1">
</a>
{{variable}}
</div>
Controller:
var app = angular.module('app',[]);
app.controller('MyController', function($scope)
{
});
jsfiddle code

Your variable binding {{variable}} should be inside controller's scope. So move ng-controller to an element that will contain variable binding.

You need to initialize the variable. See http://plnkr.co/edit/dmSNVJ3BGIeaWaddKtZe
<body ng-app="">
<button ng-click="count = 1" ng-init="count='not set'">
Increment
</button>
<span>
count: {{count}}
</span>
</body>

Use a function to set the variable:
HTML:
<div ng-app='app'>
<a ng-controller="MyController" href="#" ng-click="setVariable()">
</a>
{{variable}}
</div>
Controller:
var app = angular.module('app',[]);
app.controller('MyController', function($scope)
{
$scope.setVariable = function() {
$scope.variable = 1;
}
});

Your syntax is correct, what went wrong is you put your controller declaration in the wrong place.
You just need move it to the outer layer, no need for ng-init or function (but might be a better practice):
<div ng-app='app' ng-controller="MyController">
<a href="#" ng-click="variable=1">
click me!
</a>
{{variable}}
</div>
http://jsfiddle.net/ybavzec4/3/

Related

How to replace text on field after click Angular?

I have HTML code with inline element:
<span class="title" ng-click="update()">Rock</span>
How to replace this element on input element after click for edit?
And then after push enter on input return back span element?
I tried with directives ng-hide(), ng-show(). But I wonder
You can use either
<span class="title" ng-hide="isEdited" ng-click="update()">Rock</span>
or
<span class="title" ng-show="!isEdited" ng-click="update()">Rock</span>
or even
<span class="title" ng-if="!isEdited" ng-click="update()">Rock</span>
In any case you will want to reference something that can be truthy. For example in your controller you would have something like this in your function
/*the init function just makes sure that everything is setup
and nothing caries over from any local storage or anything
else you may be using*/
init();
init function(){
$scope.isEdited = false;
}
$scope.update = function(){
$scope.isEdited = true;
}
What you need to do is set a variable that contains the state;
<html>
<body ng-app="app">
<div ng-controller="mainController as $ctrl">
<span ng-if="!$ctrl.isInEditMode" class="title" ng-click="$ctrl.update()" ng-bind="$ctrl.spanText"></span>
<div ng-if="$ctrl.isInEditMode">
<input type="text" placeholder="Value for rock" ng-model="$ctrl.spanText" />
<button ng-click="$ctrl.update()">Done</button>
</div>
</body>
</html>
angular.module('app', [])
.controller('mainController', function($scope) {
this.isInEditMode = false;
this.spanText = 'Rock';
this.update = (function() {
this.isInEditMode = !this.isInEditMode;
}).bind(this);
});
I have prepared a Codepen that shows an possible solution: http://codepen.io/stefferd/pen/QdQrrv

Set value of input depending on element clicked in Angular

I have made the following plunker:
https://plnkr.co/edit/Ff2O2TGC4WLaD62fJmvA?p=preview
I would like the value of the input to be the item.name clicked.
Here is the code:
<body ng-app="myApp">
<div ng-controller="MyController">
<ul ng-repeat="item in collection">
<li ng-click="edit('{{item.name}}')">{{item.name}}</li>
</ul>
</div>
<input name="myinput" ng-model="myinput" />
</body>
Js:
var app = angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
$scope.collection = [
{name:'foo'},
{name:'bar'},
{name:'foobar'},
{name:'barfoo'},
];
$scope.edit = function(current_name) {
this.myinput = current_name;
console.log(current_name);
}
})
So there are a few problems here. The first is how you're passing item.name into the edit function. Instead of edit('{{item.name}}') it should simply be edit(item.name).
The next is this.myinput in the script.js isn't going to work; it needs to be $scope.myinput.
Finally, the input in the markup needs to be inside the div that defines the controller.
I've modified the Plunkr to work: https://plnkr.co/edit/mslpklTaStKEdo64FpZl?p=info
Angular expression can't have interpolation tags. Correct syntax, like if it was normal Javascript:
<li ng-click="edit(item.name)">{{item.name}}</li>
You don't have to call a function. Just do.
<li ng-click="$parent.myinput = item.name">

AngularJS Get Filtered Scope onClick

I want to get an alert button for showing the filtered object of my filtered data in Angular.
In my HTML template i can get the object i want with: {{(portals|myFilter:or| filter:search )}}
I have my button :
<a ng-href='#here' ng-click='go()' >click me</a>
and my function go() is already working but now I need the object wich I can call with : {{(portals|myFilter:or| filter:search )}} in my go() function... Any idea?
I have already tried to write the object in the button but I didnt even believed that this is too easy. There must be a way to get the same object in my controller ?
<a ng-href='#here' ng-click='go(myFilter,search)' >click me</a>
You can assign filteredItems with the following syntax:
{{filteredItem = (portals|myFilter:or| filter:search )}}
<a ng-href='#here' ng-click='go(filteredItem)' >click me</a>
You can check the below snippet for an example.
angular.module("myApp", []).controller("myCtrl", function($scope) {
$scope.items = ["apple", "banana", "orange"];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input ng-model="query"/>
{{filteredItems = (items | filter:query)}}
<div>Filtered Items: {{filteredItems}}<div>
</div>
</body>
</html>

Why does the following URL return $santize:badparse

I need to fire an ng-click when I bind the following
<a href='#' ng-click ='GotoUrl('www.cnn.com')'>CNN</a>
I get $santize:badparse
what am I doing wrong?
see this.
http://jsfiddle.net/jigardafda/08k1ztsa/1/
JS
var myApp = angular.module('myApp', []);
myApp
.controller('myCtrl', function($scope){
$scope.GotoUrl = function(url){
window.open(url);
};
});
HTML
<div ng-app="myApp">
<div ng-controller = "myCtrl">
<a href='#' ng-click ='GotoUrl("http://www.cnn.com")'>CNN</a>
</div>
</div>
You have used nested quotes. Try this:
<a href='#' ng-click ='GotoUrl("www.cnn.com")'>CNN</a>

Change Behavior of controller based on calling element

I have one controller used by two different views:
<div ng-controller="MyCtrl" ng-include="slice = false">
<span ng-repeat="value in values">{{ value }}</span>
</div>
...
<span ng-controller="MyCtrl">
<div ng-repeat="value in values">{{ value }}</div>
</span>
The controller:
var MyCtrl = function($scope){
$scope.values = ['a','fancy','array'];
// if called from span
//$scope.values = ['a','fancy','array'].slice(2);
}
I'd like to know if it is possible to detect from what element the controller is being called to change the behavior of the controller.
Update: Based on #matys84pl's answer, here is my new controller
MenuCtrl = function($scope) {
$scope.slice = true;
if($scope.slice === false) { // wont go inside
$scope.data = ['a','fancy','array'];
} else {
$scope.data = ['a','fancy','array'].slice(2);
}
console.log($scope.slice); // still true for both
}
The rule is that the controller should not be aware of the view... so you should instead pass something from the view to the controller using ngInit, like this:
<div ng-controller="MyCtrl">
<span ng-repeat="value in values">{{ value }}</span>
</div>
...
<span ng-controller="MyCtrl" ng-init="isDifferent = true">
<div ng-repeat="value in values">{{ value }}</div>
</span>
and then check isDifferent value in the controller.
Update: A plunker with working example: http://plnkr.co/edit/zUgLSQcAaZX5j6JBoQAO
<div ng-controller="MyCtrl" behavior=2>...
Please forgive my lazy js - I'm used to coffeescript
var MyCtrl = function($scope, $attrs){
if $attrs.behavior != 2
$scope.values = ['a','fancy','array'];
else
$scope.values = ['a','fancy','array'].slice(2);
}
I guess you could do something similar by swapping $attrs for $element and changing your test.

Resources