Scope of ngController doesn't update with ngInclude - javascript

Here is a Plunker: http://plnkr.co/edit/F6QM4KUU8DPNq6muInGS?p=preview
Including an html file with ng-include, having set the ng-controller in the same tag, doesn't update the controller's scope models. Using the ng-model directly inside of the html works perfectly fine, and also setting the controller inside of the included html file is working. But ng-include together with ng-controller $scope.models don't update and stay as they are.
For whatever reason if you set the model inside of the controller, it is done suring it's loading. But having a method setting the model (not included in the plunker) only changes the mdoel inside of the controller's scope and not the html one.
Also if I use an ng-include in the scope of another controller and want to access the included models return undefined or the value you set the model to. Calling methods from the included html works fine in both cases, but they can't really operate as the values are wrong.
I saw that a similar issue has already been postet and should have been resolved (https://github.com/angular/angular.js/issues/4431), but as you can see in the plunker for me it doesn't.
Do I miss something, or is this a problem of angular?
Kind Regards,
BH16
PS: Here is the code from the Plunker:
index.html - body
<body ng:controller="MainCtrl">
<input type="text" ng:model="input">{{input}} {{getInput()}}
<div ng:include="'main2.html'" ng:controller="Main2Ctrl"></div>
</body>
main2.html
<div>
<input type="text" ng:model="input2">{{input2}} {{getInput2()}}
</div>
script.js
angular.module('testApp', [])
.controller('Main2Ctrl', function($scope) {
$scope.input2 = 1234;
$scope.getInput2 = function() {
console.log("input2");
return $scope.input2;
};
})
.controller('MainCtrl', function($scope) {
$scope.input = 1234;
$scope.getInput = function() {
console.log("input");
return $scope.input;
}
});

For all of those who are are also having this issue: Just use the controllerAs syntax: http://toddmotto.com/digging-into-angulars-controller-as-syntax/
This solves all of the issues above and simplifies the code A LOT!
This is the basic idea of controllerAs (taken from the site above):
<div ng-controller="MainCtrl as main">
{{ main.title }}
<div ng-controller="AnotherCtrl as another">
Scope title: {{ another.title }}
Parent title: {{ main.title }}
<div ng-controller="YetAnotherCtrl as yet">
Scope title: {{ yet.title }}
Parent title: {{ another.title }}
Parent parent title: {{ main.title }}
</div>
</div>
</div>

It's related to that ng-include creates it's own scope.
To see what's actually happens you can try plugin(for google chrome, probably something similar exists for others browser's too): "AngularJS Batarang", it will include additional tab to dev tools.
And possible solution will be:
main2.html:
<div ng:controller="Main2Ctrl">
<input type="text" ng:model="input2"> {{input2}} {{getInput2()}}
</div>
http://plnkr.co/edit/daIehNjxWdam3NyH3ww4?p=preview

Related

ng-controller within an include that is within another controller potential scope issue

I am using node and angularjs. I have a frame like page inside an ejs that is passed content to load into the includes dynamically.
<div ng-app="thisApp">
<div ng-controller='MainCtrl'>
{{ firstMessage }}
<div id='contentFromNode' ng-include='<%= pageContent %>'></div>
</div>
</div>
<script>
var thisApp = angular.module('thisApp', []);
thisApp.controller('MainCtrl', [ '$scope', function($scope) {
$scope.firstMessage = "Main Controller Working Fine";
}])
</script>
and then the passed content might be just an html page containing something like this:
<div ng-controller='NestedCtrl' id='content-type-container'>
{{ nestedMessage }}
</div>
<script>
thisApp.controller('NestedCtrl', [function(){
var nested = this;
nested.nestedMessage = "Nested Won't Work";
}])
</script>
So I have tried $scope within the NestCtrl instead of referencing this, I have tried moving the script tag above and below (ideally this get separated eventually anyway). I have tried aliasing the controllers, however my problem is the in registration of the controller itself as I get that great Error: [$controller:ctrlreg] error. The page is loading the content fine? Any ideas what I am doing wrong here?
Seems JQlite doesn't support this. You have to include jquery or lazy load the script. Refer
AngularJS: How to make angular load script inside ng-include?

AngularJS running outside ng-app scope?

First, ng-app should be to set the area where angular take place, right? Even if there is ng-controller tag outside ng-app, they should be omitted?
However, when I test on jsfiddle (link here), it seems this is not the case:
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Hello, {{name}}!
<input ng-model="name">
</div>
</div><br><br>
<div class="not-inside-my-app">
<div ng-controller="MyCtrl">
...... Some Many other content in real case that I don't want angular to touch .......<br>
So this is to test angular is not working here.<br>
Hello, {{name}}!
<input ng-model="name">
</div>
</div><br><br>
<div ng-app="myApp">
<div ng-controller="MyCtrl2">
Hello, {{name}}!
<input ng-model="name">
</div>
</div>
Javascript
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope', MyCtrlFunction]);
function MyCtrlFunction($scope) {
$scope.name = 'Superhero';
}
myApp.controller('MyCtrl2', ['$scope', MyCtrlFunction2]);
function MyCtrlFunction2($scope) {
$scope.name = 'Non-superhero';
}
The angular code is still working in the middle div. Is my concept on ng-app wrong? Or what have I missed to limit the scope?
P.S. I know I can control the scope by using ng-controller, but it seems to be a waste on resource to do scanning on sections that I know I don't need angularJS.
Since ng-app attribute added to body tag, which is why all controllers are running.
Since angular considers first ng-app attribute and ignore other ng-app attributes. The above code is working.
NOTE: Though the code written in the html section didn't contain the body tag. You can able to insert the body tag by clicking on the gear icon in the html section of fiddle site. Which is what the main cause for this addition of ng-app attribute added to body tag. Thanks for pointing it out Durga
remove body tag <body ng-app="myApp"> from html section, there is no issue with jsfiddle.
It seems some issue with JS jsFiddle, try to run the same example in you local machine it will not work or here you get the answer:
https://www.w3schools.com/code/tryit.asp?filename=FEYVPGYHZAY5

How does childscope work on an ng-if statement? Specifically in a <SELECT> element

NOTE: I'm a new member here so I couldn't directly comment and ask for clarification.
So, my question is: How can I work around ng-if creating a child scope for a select element?
I have the following code:
HTML
<select id="project-select"
ng-if="projects.length > 0"
ng-options="project.name for project in projects"
ng-model="currentProject"
ng-change="broadcastChange('project-changed', currentProject)">
</select>
And my controller is set up in the following format:
function Controller() {
//Do code stuffz
}
angular
.module('app')
.controller('Controller', Controller);
I learned from this post that the "ng-if" is creating a child scope.
So even when the model changes, this part stays the same because it is a primitive value: (name is just a string)
<div id="current-project" class="pull-left">
<strong>Project: </strong>{{currentProject.name}}
</div>
Furthermore in the aforementioned post there were a couple options.
a. Simply change to this: ng-model="$parent.currentProject" which feels a little hacky
b. Set the object value in the controller, which I'm not entirely sure how to do. I feel like it's an easy fix, but I'm somehow overcomplicating it.
Anyway, for now I simply changed ng-if to ng-show and that's solved the problem. However, I am trying to understand Angular more deeply and I feel like this issue could be explained a little bit better to me. Thanks in advance!
What you will find with Angular scope variables is: always use a dot.
That's the mantra from the excellent ng-book
In your case, what this means is this:
You have this code:
<select id="project-select"
ng-if="projects.length > 0"
ng-options="project.name for project in projects"
ng-model="currentProject"
ng-change="broadcastChange('project-changed', currentProject)">
</select>
Which means that you are binding to a $scope variable called $scope.currentProject.
Because of the mysterious and awesome way that javascript works, this does not get updated when you are inside of a child scope.
Thankfully, the solution is actually quite simple. Instead, create an object like so:
$scope.myData = {
currentProject: ''
}
And in your markup, bind to that like so:
<select id="project-select"
ng-if="projects.length > 0"
ng-options="project.name for project in projects"
ng-model="myData.currentProject"
ng-change="broadcastChange('project-changed', myData.currentProject)">
</select>
And voila. It will update, even though it's in a child scope.
This is actually quite useful, because you now have a way to "meaningfully" group variables together. Here's some other pseudo-code to demonstrate what I mean:
$scope.projectData = {
currentProjectID: 1,
currentProjectTitle: 'My Cool Project',
projects: [
{id: 1, name: 'My Cool Project'},
{id: 2, name: 'Another Project'}
],
someOtherProperty: false
// ...etc....
}
As a side-note, this section of this article might be helpful: http://docstore.mik.ua/orelly/webprog/jscript/ch11_02.htm#jscript4-CHP-11-SECT-2.1
If all you want to do is show/hide the select element based on the projects in your 'Controller' controller scope, then ng-show is the right way to go here. In my experience, I've used ng-if when I'm conditionally loading a larger "partial" view containing numerous controls where I felt a separate scope was necessary to avoid having a very large scope (or to facilitate re-use).
You are correct. Do not use $parent in any production Angular apps. It makes your model dependent on the structure of your view, which makes your code hard to refactor and less modularized.
Binding to object properties is the way to go, as you suggested in your "b" answer. The recommended way to do this in the latest version of Angular 1.x is by using the "controller as" syntax. This method makes use of "prototypical inheritance" in javascript. There is a good explanation on this here: http://javascript.info/tutorial/inheritance
I created a plunker for you to demonstrate how binding to object properties works in nested scopes. take a look at the "controller as" syntax". also, try changing the value of ctrl.testBinding in the input, you will see that reflected in the ng-if child scope. I will try to find some links to explain this in more detail.
https://plnkr.co/edit/Gx5xbkJXgzjPSG8kajPR?p=preview
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl as ctrl">
<input ng-model="ctrl.testBinding" type="text"/>
<button ng-click="ctrl.toggle()">toggle show</button>
<div ng-if="ctrl.show">
{{ ctrl.testBinding }}
</div>
</div>
</body>
</html>
//script.js
function testController($scope) {
var vm = this;
vm.show = true;
vm.toggle = function(){
vm.show = !vm.show
}
}
angular
.module('testApp', [])
.controller('testCtrl', testController);

Angular directive with a ng-switch containing an input: can it be done cleanly?

In brief
I'm looking for a cleaner way to work around an issue that involves isolate scopes. I'm not sure there's a better workaround that what I have, but I hope so as I'm not too happy with it.
The demo
Demo on Plunkr
Contains both a directive that shows the problem, and another one with the dirty fix.
Change the values of the inputs and see it doesn't get propagated for one of them.
The story
I wrote a directive that contains a ng-switch. The code is:
angular.module('core')
.directive('otherSearchField', function() {
return {
templateUrl: 'otherSearchField.html',
restrict: 'E',
scope: {
field: '=',
placeholder: '#',
condition: '#searchWhen'
}
};
});
Its template is:
<section ng-switch="condition">
<div ng-switch-when="true">
<input type="text" ng-model="field" placeholder="{{placeholder}}">
<button ng-click="search()">Search</button>
</div>
<div ng-switch-default>
{{field}}
</div>
</section>
I could rewrite it as a ng-if, but what matters really is that in both cases, a new scope is created by ng-switch or ng-if.
I use the directive this way:
<div ng-controller="Ctrl">
<other-search-field field="query.city" placeholder="City" search-when="{{edition.city}}"></other-search-field>
</div>
The issue
As you notice, in the directive template, we have an input bound to "field". That one is bound to the calling template via the = notation in the directive definition.
However, because we're not using the object notation, entering something in the input modifies the field in the ng-switch's scope, but does not propagate out of it.
A (dirty) solution
My current solution is to use the object notation in the directive's template, which means I need to pass the containing object to the directive, and the name of the property I want to modify.
<section ng-switch="condition">
<div ng-switch-when="true">
<input type="text" ng-model="fieldParent[field]" placeholder="{{placeholder}}">
<button ng-click="search()">Search</button>
</div>
<div ng-switch-default>
{{fieldParent[field]}}
</div>
</section>
Usage:
<my-search-field field-parent="query" field="customer" placeholder="Customer" search-when="{{edition.customer}}"></my-search-field>
This works: I'm using the object notation so the changes on the input propagate all the way up (see on the Plunkr linked above).
So ?
Hmm, I'm not too happy to pass an entire object when only one of its properties is needed though. Is there a better way ?
NB
Note I could also, in this case, use multiple ng-show as they don't create their own scope. But I'm interested in the more general issue shown here, not in this specific case.
Thanks for reading all the way. Kudos to you !
In your otherSearchField.html template, you can access the $parent $scope's field property, thereby accessing the isolate scope that your directive <other-search-field> is using.
DEMO
<section ng-switch="condition">
<div ng-switch-when="true">
<input type="text" ng-model="$parent.field" placeholder="{{placeholder}}">
<button ng-click="search()">Search</button>
<div>value in the template, in "switch": {{$parent.field}}</div>
</div>
<div ng-switch-default>
{{field}}
</div>
</section>
<div>
value in the template, out of "switch": {{field}}
</div>

AngularJS - ng-include ng-controller and scope not binding

I have the following main view
<div ng-include="'otions.html'"></div>
and options.html has the following
<div ng-controller="OptionsController">Options</div>
<input type="text" ng-model="keyword" value="{{keyword}}" />
<button ng-click="search()">Search</button>
But "keyword" is not binding to the scope in OptionsController.
app.controller('OptionsController',
['$scope', function($scope) {
$scope.keyword = "all";
$scope.search = function() {
console.log("hello")
};
}]);
when I click on the button, I don't see hello and the keyword all doesn't appear in the input text.
I tried moving the ng-controller part as follows
<div ng-controller="OptionsController" ng-include="'otions.html'"></div>
And things work as expected.
I read through the answers in AngularJS - losing scope when using ng-include - and I think my problem is related, but just need some more explanation to undertstand what's going on.
You should write options.html like this:
<div ng-controller="OptionsController">Options
<input type="text" ng-model="keyword" value="{{keyword}}" />
<button ng-click="search()">Search</button>
</div>
OptionsController should be put in the outer html element.
i have face same problem,
Under main tag it will be work fine but, When bind some data to nav.html it not work.
find this link
AngularJS - losing scope when using ng-include
inside include its work child scope.
better option to create custom directive its easy solution

Categories

Resources