angularjs - What sense does have a new child scope inaccessible from parent controller? (created by ng- directives) -



angularjs - What sense does have a new child scope inaccessible from parent controller? (created by ng- directives) -

in angular.js directives create kid scopes. (ng-include, ng-if, etc)

i know there ways solve it, illustration declaring variable in scope of controller. uncomment //$scope.inner = '1234' , removeng-init="inner='1234'and work. solution utilize object in parent scope containing variable.

still not create sense me.

what sense have scope without controller? practical utilize have these new kid scope?

this example.

class="snippet-code-js lang-js prettyprint-override">var app = angular.module('app', []); app.controller('ctrl', ['$scope', function($scope) { $scope.result = "result"; $scope.outer = "outer"; //$scope.inner = "1234"; $scope.test1 = function() { if ($scope.inner) { $scope.result = $scope.inner; } else { alert("inner not accesible"); } } $scope.test2 = function() { if ($scope.outer) { $scope.result = $scope.outer; } else { alert("inner2 not accesible"); } } }]); class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl" > <script type="text/ng-template" id="/tpl.html"> <input type="text" ng-init="inner='inner'" ng-model="inner"></input> <button ng-click="test1()">test1</button> </script> <div> <ng-include src="'/tpl.html'"></ng-include> <br/> <input type="text" ng-model="outer"></input> <button ng-click="test2()">test2</button> <p>{{result}}</p> </div> </div>

first need understand scopes , controllers 2 separate concepts.

the scope object refers application model while controller constructor function utilize manipulate scope.

so, "from angular's point of view", it's acceptable have scope not augmented controller.

the thought creating new kid scopes have logical way separate application's model. imagine having 1 scope entire application? have careful not override functions or properties while manipulating scope in controllers. since kid scopes prototypically inherit parent scope don't have worry that.

one practical illustration of usability of these kid scopes is, example, when have 2 ng-repeat directives side-by-side, "under" same scope. if didn't create own kid scopes, how have access $index, $first, $last, etc... properties each of ng-repeat directives? without kid scopes both polluting "parent" scope same properties, overriding each other.

you can read more info on scopes here , on controllers here.

angularjs angularjs-scope

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -