I have this code:
<!doctype html>
<html ng-app="myApp" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function ($scope) {
$scope.count = 0;
$scope.increment = function (){
$scope.count = $scope.count + 1;
}
});
</script >
<div ng-controller="FirstCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
what is wrong with it?
When I work without controllers it's works fine but when I use app and app.controller It will not work. why is that? am I doing something wrong?
The "Controller as" syntax is only available from version 1.1.5+
By what i know when using "Controller as" and you want to reference a variable with the assigned controller alias (in your case "app1") then you should assing the variables with "this." syntax in the controller, or access the variables without the "app1", then it will try to get it from the scope.
http://jsbin.com/zehagogoku/3/edit
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function ($scope) {
this.count = 0;
this.increment = function (){
this.count = this.count + 1;
};
$scope.count = 0;
$scope.increment = function(){
$scope.count = $scope.count + 1;
};
});
You are mixing styles here. In your HTML, you are using the Controller As syntax, where you write FirstCtrl as app1. This makes an object called app1 on the scope, which is an instance of your FirstCtrl. app1.count, app1.increment(), etc. would be properties of the FirstCtrl object.
In your controller, you are not creating properties on the controller. You are, instead, assigning your variables as properties on the $scope object.
Using $scope has advantages, in that it is essentially a global object, so it is accessible from everywhere in your app. However, it's disadvantages are also rooted in the fact that it's a global object.
You can either change your javascript to match the Controller As syntax, as shown:
app.controller("FirstCtrl",function () {
//create an alias to this for consistent reference
var app1 = this;
app1.count = 0;
app1.increment = function (){
app1.count += 1;
};
});
Or, you can change your HTML to use $scope:
<div ng-controller="FirstCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
change in the javascript:
$scope.count += 1;
note, you don't have to reference $scope inside the HTML, as it's presence is implicit. However, this line in your javascript $scope.count = this.count + 1;
will never work in either case, again because you are mixing styles.
Also, as mentioned, Controller As syntax requires Angular 1.1.5 or higher.
Related
I have an angular app where in my index.html i have a variable inside a tag, like this:
<script type="text/javascript">
let global = 5;
</script>
I need to read and edit the value of this variable, inside an angular component, but I do not know how to do it.
I saw that it is possible to read the value if you create the variable inside the "window" object of javascript (window.global = 5) and then use it in angular component, but i think it would not work for me because i need that variable to be outside, as specified above.
Is it possible? Any ideas?
The keyword declare to the rescue: first, declare your global with var (let doesn't work)
<script type="text/javascript">
var someVar = 5;
</script>
and access it in, say, Angular component:
declare var someVar;
// ...
this.foo = someVar;
https://stackblitz.com/edit/angular-ivy-zjpnzq?file=src%2Fapp%2Fhello.component.ts
Finally I used an aproximation of #robin-zigmond answer. I changed let to var in the script tag and in my angular component I access the variable using:
window["global"]
I can edit the value inside a component using, for example:
window["global"] = 6
Moreover, I tried #mbojko answer and it worked too.
You can pass the window varaible to the scope in your controller.
<!DOCTYPE html>
<html>
<script>window.HELLO_MSG = 'Hello,';</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ wlcmMsg + " " + firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.wlcmMsg = window.HELLO_MSG;
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Or you can inject the whole window object like here:
How to inject window into a service?
I'm new to angular and little bit confused with it. So basically I created a simple button and i want to run function foo() whitch assigns variable var one = 1; to $scope and outputs it in <p>{{one}}<p> every time its clicked like in live typing but this seems not working. Please provide me a solution to this.
<html ng-app="app">
<!-- Body tag augmented with ngController directive -->
<body ng-controller="myController">
<input type="text" ng-model="name">
<p>{{name}}</p>
<p>{{one}}</p>
<button ng-click="foo()">1</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="controller.js"></script>
</body>
</html>
controller:
var app = angular.module('app',[]);
app.controller('myController', ['$scope',function($scope){
var one = 1;
$scope.name = name;
function foo(){
return $scope.one = one;
}
}]);
function foo() dont exist in $scope your controller "myController"
if you declaration:
$scope.foo = function(){}
in your controller, then this work for you
when you are calling controller function from the html, controller function should be scope. Other wise ng-click directive doesn't recognize the function.
same concept goes to binding variable to html. only scope variables can directly bind to html using curly brackets. so inside foo function var one should assign to scope.one in order to display it in the html.
angular.module("app",[])
.controller("ctrl",function($scope){
var one = 1;
$scope.name = name;
$scope.foo = function(){
$scope.one = one;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="name">
<p>{{name}}</p>
<p>{{one}}</p>
<button ng-click="foo()">1</button>
</div>
Basically I am trying to access controller scope property from directive's controller function. I am doing it through $parent property. It works fine for static directive but not for dynamically created directive.
please have a look on my plunker
Dynamic Directive
In a plunker, when I click on folder with Id = 1. all goes good and folder path shows as "1 path". Same goes for folder with Id = 2.
But it does not work for dynamically appended folder with Id = n
I am somewhat new to angular. Any help would be much appreciated.
Updated Answer
In light of the latest requirement:
I am trying to call the directive function (i.e updateMap) from
controller.
You can use a Service to share variables between Controllers and Isolated Directives. In the example below, the Service holds the function that will be executed. Each directive when clicked will set the Service's function to it's own updateMap() function. Then the Controller in onFolderPathClicked() calls the Services executeFunction() function, which runs the previously set function.
script.js:
var module = angular.module('testApp', []);
module.service('updateMapService', function(){
var updateMapFunction = null;
this.executeFunction = function(){
updateMapFunction();
};
this.setFunction = function(fn){
updateMapFunction = fn;
};
});
module.controller('crtl', function($scope, updateMapService) {
$scope.onFolderPathClicked = function(){
updateMapService.executeFunction();
};
});
module.directive('folder', function($compile) {
return {
restrict: 'E',
scope: {
id: '#',
folderPath: "="
},
template: '<p ng-click="onFolderClicked()">{{id}}</p>',
controller: function($scope, $element, updateMapService) {
$scope.onFolderClicked = function(){
updateMapService.setFunction(updateMap);
addFolder();
};
var addFolder = function() {
$scope.folderPath = $scope.id + ":click here for calling update map";
var el = $compile('<folder id="n" folder-path="folderPath"></folder>')($scope);
$element.parent().append(el);
};
var updateMap = function() {
alert('inside updateMap()..' + $scope.id);
}
}
}
});
index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="testApp" ng-controller="crtl">
<div>FolderPath : <a ng-click="onFolderPathClicked()">{{ folderPath }}</a> </div>
<folder id="1" folder-path="folderPath"></folder>
<folder id="2" folder-path="folderPath"></folder>
</div>
</html>
You could also move folder-path into a Service to save from passing it in as an attribute. The code smell being that passing it in as an attribute means doing so twice, whereas in a Service it means setting it and getting it once (code reuse).
(simple plunkr demo here)
SUMMARY:
There is a leak using ng-repeat after the 2nd wave iterating over an 'array' of custom objects like this :
<div ng-repeat="d_sampleObject in mySampleObjects">
{{d_sampleObject.description}}
</div>
Memory profile reveals an extra 'd_sampleObject' left over and not de-referenced. More details (via a controller and an injected service) below. A simple demonstration also in the provided plunkr link. Any thoughts and help greatly appreciated in advance!
NOTE: 'mySampleObjects' is an array of the following instances:
ml.MySampleObject = function (id) {
this.id = id;
this.description = 'this is object #:' + ' '+id;
}
DETAILS:
I have a custom object model that reflects the business domain objects that we utilize in our AngularJS app. I have found that when I pass an instance of one of my custom objects to ng-repeat, a reference is kept to it (I think by Angular) and memory is not freed. This happens on the second 'wave' (click on 'refresh') of the ng-repeat as it iterates, again, over its array of objects. This leak is exposed in my Profile tests (in Chrome) . Here is a short example in plunkr. Click on 'refresh' button once (or more) to see the extra 'd_sampleObject' object instance that is leaked (in Chrome Profile Inspection). Note, the 'd_sampleObject' name is only used when passed to ng-repeat. I have included screenshots of the extra object instance ('d_sampleObject') that is being leaked further below. Why is there a leak and how can it be avoided?
(Note, I have found if I don't iterate over my object collection (JS array) thru an object but rather thru a primitive index ('integer'), there is no leak. The leak seems to only happen when I use an object reference as a result of ng-repeat iterations)
SIMPLE HTML:
<!DOCTYPE html>
<html ng-app="memoryleak">
<head>
<meta charset="utf-8" />
<title>Memory Leak Test</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.13/angular.min.js" data-semver="1.3.13"></script>
<script src="app.js"></script>
<script src="dataservice.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="d_sampleObject in mySampleObjects">
{{d_sampleObject.description}}
</div>
<br>
<button ng-click="redo()">Number of refreshes: {{numRedos}}!</button>
</body>
</html>
SIMPLE APP.JS
(function(ml) {
var app = angular.module('memoryleak',['servicemodule']);
app.controller('MainCtrl', ['$scope', 'dataservice', function($scope, dataservice) {
$scope.redo = function () {
$scope.numRedos++;
$scope.mySampleObjects = dataservice.myObjectCollection;
dataservice.redo();
}
$scope.redo();
}]);
}(window.MEMLEAK = window.MEMLEAK || {}));
SIMPLE dataservice.js
(function(ml) {
'use strict';
var serviceModule = angular.module('servicemodule',[]);
serviceModule.factory('dataservice', ['$rootScope', '$http',
function ($rootScope, $http) {
this.myObjectCollection = [];
this.redo = function () {
this.numRedos++;
// that.myObjectCollection = [];
this.myObjectCollection.length = 0;
for (var i = 0; i < 10; i++) {
var sampleObject = new ml.MySampleObject(i);
that.myObjectCollection.push(sampleObject);
}
sampleObject=null;
}
ml.MySampleObject = function (id) {
this.id = id;
this.description = 'this is object #:' + ' '+id;
}
return this; //return the entire service to make methods accessible to dependents
}]);
}(window.MEMLEAK = window.MEMLEAK || {}));
SCREENSHOT 1: (FIRST PAGE LOAD--there are 10 'mySampleObjects' created)
SCREENSHOT 2: (CLICKED ON REFRESH--there is an 11th mySampleObject created/leaked with a reference to the instance name of 'd_sampleObject' passed to ng-repeat.)
There is acknowledgement by the AngularJS folks that this is indeed a bug in the framework. A fix and pull request has been posted.
I have also asked what the timeframe is for a formal fix.
I have a controller with such:
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
If next() (with ngClick) is called 3 times, we get:
//1
//2
//3
but if back() (with ngSwipeLeft) is called it returns
//-1
when I'm obviously expecting
//2
What am I missing here?
update: including ngTouch details - this seems to be the problem.. ngTouch is included.
When I watch the myVar value - its like it exists twice - one with the ngSwipeLeft call, and one with the ngClick call
Your snippet looks fine to me. You need to provide more code, error might be somewhere else. Look at the code below.
<!doctype html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-touch.min.js"></script>
<script>
var app = angular.module('myapp',['ngTouch']);
var controller = app.controller('mycontroller', ['$scope',function($scope){
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}]);
</script>
</head>
<body ng-controller="mycontroller">
<div>
<h1>MyVar: {{myVar}}!</h1>
<input type="button" value="back" ng-click="back()"/>
<input type="button" value="next" ng-click="next()"/>
</div>
</body>
</html>
Ok, so I've figured out my problem - I wasn't providing enough detail in the question - but if someone runs into something similar in the future, heres what was going on:
I was declaring my controller with ng-controller="myCtrl" in the templates, but also using routing, where I declared my controller like:
$routeProvider.when('/', {
templateUrl: 'myUrl.html',
controller: 'myCtrl'
});
This was instantiating the controller twice, and obviously causing problems (although that seemed to the only one to surface for now).
Removing the controller definition from the routing or the view did the trick.
need to see your html not sure about your problem, here is a sample working code,
<div ng-app="myapp">
<div ng-controller="IncDecController">
<span>current value is {{myVar}}</span>
<img src="https://angularjs.org/img/AngularJS-large.png" ng-swipe-left="back()"></img>
<button ng-click="next()">next</button>
</div>
</div>
script:
angular.module('myapp', ['ngTouch'])
.controller('IncDecController', ['$scope', function ($scope) {
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}])