M
M
Maks Burkov2017-04-12 15:34:01
JavaScript
Maks Burkov, 2017-04-12 15:34:01

How to properly use $scope in Angular?

In theory, it should output > 12, I get the wrong output, who will explain what's wrong?
Testing with Angular as a beginner!

<body>
<div ng-controller="MaksController">
    <h1>Hello from angular! </h1>
    <p ng-if="controller > 12">Controller > 12</p> 
    <p ng-if="controller > 20">Controller > 20</p>
    <p>The controller value is: {{controller}}</p>
</div>
<script>
    var module = angular.modules("myApp",[]);
    module.controller("MaksController",controllerFunction);
    function controllerFunction($scope) {
       $scope.controller = 15;
       console.log("Maks Controller called! ");
    }
</script>
</body>

fdbf14bea91e4fd58400a8ee9fbfbb84.jpg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Philipp, 2017-04-12
@Maks00088

You had the following errors
The corrected version plnkr.co/edit/hJVCAByn7ncyAmao9pKI?p=info
ng-app is not allowed here is the standard HTML validator warning. This is fine.
Instead of ng-if, it is better to use ng-show, because this is a more efficient operation.
DOM transformation takes more time than just changing a class.
Use ng-if only when you have a critical need to change the document's DOM structure.
For example, you have some incompatible library that needs to work with id="abc". This is usually some third party service that needs to manipulate the DOM and is hardcoded with id="abc":

<div ng-if="switchA"><div id="abc">A</div></div>
<div ng-if="switchB"><div id="abc">B</div></div>

ng-show can have a negative performance impact when you have multiple child components and controllers inside because observers have been added to them, etc. That is, in the case of a complex nested structure with ng-model or ng-bind, etc. it's better to use ng-if. This will help save memory.
In the case of simple nested structures, ng-show will be more performant.
For example, for this option it is better to use ng-show:
<div ng-repeat="user in users">
  {{user.name}}
  <div ng-show="user.isStar">*</div>
</div>

But
<div ng-repeat="user in users">
  {{user.name}}
  <div ng-if="user.isStar"><custom-star-component user="user"></custom-star-component></div>
</div>

A
Anton, 2017-04-12
@sHinE

In the console, your message Maks Controller called! output?
I don’t remember exactly in which case the application bootstrap itself, perhaps you need to hang the ng-app directive on the body or manually launch the bootstrap method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question