Rectangle 27 6

That answer explains the process in technical great detail. So, I'm gonna tell it in layman's terms.

AngularJS makes itself work by using dirty checking, there are sets of values that angular is watching. Everytime something big happens, (a click, a function call in controller), angular runs a digest cycle, comparing the watched values to see if there is any change. If there is a change, depending on the watcher, angular will take necessary action (update view, fire a callback, update route).

When you use default directives and no jquery event handling in controller, you will be fine. However, if you do, you need to know that you are NOT in the angular's digest cycle. Which means the watchers will not fire until a digest occurs.

You need to know when are you updating a variable that is being watched. Mostly it is custom DOM event (or jquery events). When it is the case, you need to let angular know that something is changed and it needs to re-check what happened (ie. update watchers).

scope.$apply()

Bear in mind that you cannot run an $apply() if you are already in the angular's digest cycle. It will throw an error like $digest already in progress.

javascript - AngularJS and location.path() - Stack Overflow

javascript html angularjs
Rectangle 27 79

//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
  $scope = $scope || angular.element(document).scope();
  if(forceReload || $scope.$$phase) {
    window.location = url;
  }
  else {
    //only use this if you want to replace the history stack
    //$location.path(url).replace();

    //this this if you want to change the URL and add it to the history stack
    $location.path(url);
    $scope.$apply();
  }
};

You should probably use the $window service instead of directly using the window object to avoid issues when testing. code.angularjs.org/1.1.5/docs/api/ng.$window

i have also written a seperate back history stack

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - In Angular, how to redirect with $location.path as $http....

javascript model-view-controller angularjs
Rectangle 27 6

$window.location.href.

The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.

$window.location.href = "/your/path/here";

javascript - AngularJS $location.path() not reloading data of the dest...

javascript angularjs
Rectangle 27 90

Communication with Web workers happens through a messaging mechanism. Intercepting these messages happens in a call back. In AngularJS, the best location to put a web worker is in a service as you duly noted. The best way to deal with this is to use promises, which Angular works amazingly with.

Here is an example of a webworker in a service

var app = angular.module("myApp",[]);

app.factory("HelloWorldService",['$q',function($q){

    var worker = new Worker('doWork.js');
    var defer = $q.defer();
    worker.addEventListener('message', function(e) {
      console.log('Worker said: ', e.data);
      defer.resolve(e.data);
    }, false);

    return {
        doWork : function(myData){
            defer = $q.defer();
            worker.postMessage(myData); // Send data to our worker. 
            return defer.promise;
        }
    };

});

Now whatever external entity that accesses Hello World service need not care about the implementation details of HelloWorldService - HelloWorldService could probably process the data over a web worker, over http or do the processing right there.

It is a reference to the external js file that contains the code for the web-worker.

How would I reference a file with angular routes in place? Right now it has to and async load the script from my server. Can I have stored right on the client?

If doWork is called again before the worker finishes, won't defer be overwritten? The second promise would then resolve with the first result, and the first promise would never resolve.

@hughes From my read of the code, yes, I think you are right. This code needs to be modified to provide a new defer to resolve each time doWork(data) is called.

javascript - AngularJS and web workers - Stack Overflow

javascript angularjs web-worker
Rectangle 27 89

Communication with Web workers happens through a messaging mechanism. Intercepting these messages happens in a call back. In AngularJS, the best location to put a web worker is in a service as you duly noted. The best way to deal with this is to use promises, which Angular works amazingly with.

Here is an example of a webworker in a service

var app = angular.module("myApp",[]);

app.factory("HelloWorldService",['$q',function($q){

    var worker = new Worker('doWork.js');
    var defer = $q.defer();
    worker.addEventListener('message', function(e) {
      console.log('Worker said: ', e.data);
      defer.resolve(e.data);
    }, false);

    return {
        doWork : function(myData){
            defer = $q.defer();
            worker.postMessage(myData); // Send data to our worker. 
            return defer.promise;
        }
    };

});

Now whatever external entity that accesses Hello World service need not care about the implementation details of HelloWorldService - HelloWorldService could probably process the data over a web worker, over http or do the processing right there.

It is a reference to the external js file that contains the code for the web-worker.

If doWork is called again before the worker finishes, won't defer be overwritten? The second promise would then resolve with the first result, and the first promise would never resolve.

@hughes From my read of the code, yes, I think you are right. This code needs to be modified to provide a new defer to resolve each time doWork(data) is called.

javascript - AngularJS and web workers - Stack Overflow

javascript angularjs web-worker
Rectangle 27 501

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak. But for me this is a workaround, that i don't need to use, if i use ng-bind.

{{}}

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.

I am currently building a big single page app (~500 bindings per view). Changing from {{}} to strict ng-bind did save us about 20% in every scope.$digest.

If you use a translation module such as angular-translate, always prefer directives before brackets annotation.

{{'WELCOME'|translate}}
<span ng-translate="WELCOME"></span>

If you need an filter function, better go for a directive, that actually just uses your custom filter. Documentation for $filter service

In Angular 1.3x the "bindonce" functionality got introduced. Therefore you can bind the value of an expression/attribute once (will be bound when != 'undefined').

<ul>  
  <li ng-repeat="item in ::items">{{item}}</li>
</ul>  
<a-directive name="::item">
<span data-ng-bind="::value"></span>

ng-repeat to output some data in the table, with multiple bindings per row. Translation-bindings, filter outputs, which get executed in every scope digest.

From what I can tell from the source (as of 2014-11-24), curly interpolation is handled just like a directive (see addTextInterpolateDirective() in ng/compile.js). It also uses $watch so the DOM is not touched if the text doesn't change, it does not "dirty check and refresh" it on every $digest as you claim. What is done on every $digest though is that the interpolated result string is calculated. It's just not assigned to the text node unless it changes.

I wrote a performance test for internal evaluation. It had 2000 entries in an ng repeat and displayed 2 attributes in the object, so 2000x2 bindings. The bindings differ in: First binding was just the binding in a span. The seconds had a binding and some plain html in it. The result: ng-bind was faster about 20% per scope apply. Without checking the code, it seems, that additional plain html with a curly expression in a html element takes even more time.

Just want to point out that according to the tests here: jsperf.com/angular-bind-vs-brackets seem to show that brackets are FASTER than bind. (Note: bars are ops per second, thus longer is better). And as previous comments point out, their watching mechanisms are ultimately identical.

Because you'r not providing any source, i give you one: ng-perf.com/2014/10/30/ "ng-bind is faster because its simpler. interpolation has to go through extra steps of verifying context, jsonification of values and more. that makes it slightly slower."

javascript - AngularJS : Why ng-bind is better than {{}} in angular? -...

javascript angularjs ng-bind
Rectangle 27 498

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak. But for me this is a workaround, that i don't need to use, if i use ng-bind.

{{}}

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.

I am currently building a big single page app (~500 bindings per view). Changing from {{}} to strict ng-bind did save us about 20% in every scope.$digest.

If you use a translation module such as angular-translate, always prefer directives before brackets annotation.

{{'WELCOME'|translate}}
<span ng-translate="WELCOME"></span>

If you need an filter function, better go for a directive, that actually just uses your custom filter. Documentation for $filter service

In Angular 1.3x the "bindonce" functionality got introduced. Therefore you can bind the value of an expression/attribute once (will be bound when != 'undefined').

<ul>  
  <li ng-repeat="item in ::items">{{item}}</li>
</ul>  
<a-directive name="::item">
<span data-ng-bind="::value"></span>

ng-repeat to output some data in the table, with multiple bindings per row. Translation-bindings, filter outputs, which get executed in every scope digest.

From what I can tell from the source (as of 2014-11-24), curly interpolation is handled just like a directive (see addTextInterpolateDirective() in ng/compile.js). It also uses $watch so the DOM is not touched if the text doesn't change, it does not "dirty check and refresh" it on every $digest as you claim. What is done on every $digest though is that the interpolated result string is calculated. It's just not assigned to the text node unless it changes.

I wrote a performance test for internal evaluation. It had 2000 entries in an ng repeat and displayed 2 attributes in the object, so 2000x2 bindings. The bindings differ in: First binding was just the binding in a span. The seconds had a binding and some plain html in it. The result: ng-bind was faster about 20% per scope apply. Without checking the code, it seems, that additional plain html with a curly expression in a html element takes even more time.

Just want to point out that according to the tests here: jsperf.com/angular-bind-vs-brackets seem to show that brackets are FASTER than bind. (Note: bars are ops per second, thus longer is better). And as previous comments point out, their watching mechanisms are ultimately identical.

Because you'r not providing any source, i give you one: ng-perf.com/2014/10/30/ "ng-bind is faster because its simpler. interpolation has to go through extra steps of verifying context, jsonification of values and more. that makes it slightly slower."

javascript - AngularJS : Why ng-bind is better than {{}} in angular? -...

javascript angularjs ng-bind
Rectangle 27 498

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak. But for me this is a workaround, that i don't need to use, if i use ng-bind.

{{}}

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.

I am currently building a big single page app (~500 bindings per view). Changing from {{}} to strict ng-bind did save us about 20% in every scope.$digest.

If you use a translation module such as angular-translate, always prefer directives before brackets annotation.

{{'WELCOME'|translate}}
<span ng-translate="WELCOME"></span>

If you need an filter function, better go for a directive, that actually just uses your custom filter. Documentation for $filter service

In Angular 1.3x the "bindonce" functionality got introduced. Therefore you can bind the value of an expression/attribute once (will be bound when != 'undefined').

<ul>  
  <li ng-repeat="item in ::items">{{item}}</li>
</ul>  
<a-directive name="::item">
<span data-ng-bind="::value"></span>

ng-repeat to output some data in the table, with multiple bindings per row. Translation-bindings, filter outputs, which get executed in every scope digest.

From what I can tell from the source (as of 2014-11-24), curly interpolation is handled just like a directive (see addTextInterpolateDirective() in ng/compile.js). It also uses $watch so the DOM is not touched if the text doesn't change, it does not "dirty check and refresh" it on every $digest as you claim. What is done on every $digest though is that the interpolated result string is calculated. It's just not assigned to the text node unless it changes.

I wrote a performance test for internal evaluation. It had 2000 entries in an ng repeat and displayed 2 attributes in the object, so 2000x2 bindings. The bindings differ in: First binding was just the binding in a span. The seconds had a binding and some plain html in it. The result: ng-bind was faster about 20% per scope apply. Without checking the code, it seems, that additional plain html with a curly expression in a html element takes even more time.

Just want to point out that according to the tests here: jsperf.com/angular-bind-vs-brackets seem to show that brackets are FASTER than bind. (Note: bars are ops per second, thus longer is better). And as previous comments point out, their watching mechanisms are ultimately identical.

Because you'r not providing any source, i give you one: ng-perf.com/2014/10/30/ "ng-bind is faster because its simpler. interpolation has to go through extra steps of verifying context, jsonification of values and more. that makes it slightly slower."

javascript - AngularJS : Why ng-bind is better than {{}} in angular? -...

javascript angularjs ng-bind
Rectangle 27 487

One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

Using the service in a controller:

function Ctrl2($scope, sharedProperties) {
    $scope.prop2 = "Second";
    $scope.both = sharedProperties.getProperty() + $scope.prop2;
}

This is described very nicely in this blog (Lesson 2 and on in particular).

I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.

var property = { Property1: 'First' };
var property = 'First';

UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:

Binding to static copies of the shared value (in myController1)

  • Binding to a primitive (string)
  • Binding to an object's property (saved to a scope variable)

Binding to shared values that update the UI as the values are updated (in myController2)

  • Binding to a function that returns a primitive (string)

In this case - how would the scope of Ctrl2 "know" when sharedProperties.getProperty() changes value?

If you wanted your UI to update each time the property changes you can change both to be a function and it will be called/re-evaluated during the angular digest process. See this fiddle for an example. Also if you bind to an object's property you can use it directly in your view and it will update as the data is changed similar to this example.

If you want to detect and react to changes in your controller an option is to add the getProperty() function to the scope and use $scope.$watch like in this example. Hope these examples help!

There is a problem here as services should be stateless. Storing off a property inside of a service is wrong (but convenient). I started using $cacheFactory to read and write data. I use almost an identical service as Gloopy but instead of storing state in the service, it is now in the cache. First create a cache service: angular.module('CacheService', ['ng']) .factory('CacheService', function($cacheFactory) { return $cacheFactory('CacheService'); }); Include in in your app.js, inject it in the service, use it like so: return CacheService.get(key); or CacheService.put(key, value);

Trying to grok how and why this answer uses .service instead of .factory as described in the Angular docs. Why is this answer voted so high when the documentation uses a different method?

javascript - AngularJS: How can I pass variables between controllers? ...

javascript angularjs angularjs-controller
Rectangle 27 484

One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

Using the service in a controller:

function Ctrl2($scope, sharedProperties) {
    $scope.prop2 = "Second";
    $scope.both = sharedProperties.getProperty() + $scope.prop2;
}

This is described very nicely in this blog (Lesson 2 and on in particular).

I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.

var property = { Property1: 'First' };
var property = 'First';

UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:

Binding to static copies of the shared value (in myController1)

  • Binding to a primitive (string)
  • Binding to an object's property (saved to a scope variable)

Binding to shared values that update the UI as the values are updated (in myController2)

  • Binding to a function that returns a primitive (string)

In this case - how would the scope of Ctrl2 "know" when sharedProperties.getProperty() changes value?

If you wanted your UI to update each time the property changes you can change both to be a function and it will be called/re-evaluated during the angular digest process. See this fiddle for an example. Also if you bind to an object's property you can use it directly in your view and it will update as the data is changed similar to this example.

If you want to detect and react to changes in your controller an option is to add the getProperty() function to the scope and use $scope.$watch like in this example. Hope these examples help!

There is a problem here as services should be stateless. Storing off a property inside of a service is wrong (but convenient). I started using $cacheFactory to read and write data. I use almost an identical service as Gloopy but instead of storing state in the service, it is now in the cache. First create a cache service: angular.module('CacheService', ['ng']) .factory('CacheService', function($cacheFactory) { return $cacheFactory('CacheService'); }); Include in in your app.js, inject it in the service, use it like so: return CacheService.get(key); or CacheService.put(key, value);

Trying to grok how and why this answer uses .service instead of .factory as described in the Angular docs. Why is this answer voted so high when the documentation uses a different method?

javascript - AngularJS: How can I pass variables between controllers? ...

javascript angularjs angularjs-controller
Rectangle 27 302

You'll have to find the index of the person in your persons array, then use the array's splice method:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );

this is a better answer; works when the list has been filtered so that that index in the view is not the same as in the array in scope.

This is indeed the better answer. Note that in addition to the filtered lists use case mentioned by Andrew, this approach also covers the case in which you delete multiple persons and the Ajax requests for these deletes return out of order. If you have use the row indexes from before the Ajax call return, you'll end up removing the wrong rows.

Is better in some cases, but with indexOf you have to iterate over all the items to find the right one, in the Josh answer you get the index and the item faster

javascript - AngularJS How to remove an Item from scope - Stack Overfl...

javascript angularjs
Rectangle 27 302

You'll have to find the index of the person in your persons array, then use the array's splice method:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );

this is a better answer; works when the list has been filtered so that that index in the view is not the same as in the array in scope.

This is indeed the better answer. Note that in addition to the filtered lists use case mentioned by Andrew, this approach also covers the case in which you delete multiple persons and the Ajax requests for these deletes return out of order. If you have use the row indexes from before the Ajax call return, you'll end up removing the wrong rows.

Is better in some cases, but with indexOf you have to iterate over all the items to find the right one, in the Josh answer you get the index and the item faster

javascript - AngularJS How to remove an Item from scope - Stack Overfl...

javascript angularjs
Rectangle 27 64

From what I understand they are all pretty much the same. The major differences are their complexities. Providers are configurable at runtime, factories are a little more robust, and services are the simplest form.

Also this gist may be helpful in understanding the subtle differences.

var myApp = angular.module('myApp', []);

//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!";
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!";
        }
    };
});

//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {
    // In the provider function, you cannot inject any
    // service or factory. This can only be done at the
    // "$get" method.

    this.name = 'Default';

    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!";
            }
        };
    };

    this.setName = function(name) {
        this.name = name;
    };
});

//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});


function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {

    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}

So one way of looking at them, is that in order of complexity they go Provider > Factory > Service > Value ?

Thats one way to look at it, another would be to think of Factory and Service as abstractions of Provider. Someone correct me if I am wrong but Factory and Service use Provider under the hood. Which is why provide is the "Closest to the metal" version. I believe Value is a way to define constants that can then be used application wide.

javascript - AngularJS : What is a factory? - Stack Overflow

javascript angularjs angularjs-factory
Rectangle 27 64

From what I understand they are all pretty much the same. The major differences are their complexities. Providers are configurable at runtime, factories are a little more robust, and services are the simplest form.

Also this gist may be helpful in understanding the subtle differences.

var myApp = angular.module('myApp', []);

//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!";
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!";
        }
    };
});

//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {
    // In the provider function, you cannot inject any
    // service or factory. This can only be done at the
    // "$get" method.

    this.name = 'Default';

    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!";
            }
        };
    };

    this.setName = function(name) {
        this.name = name;
    };
});

//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});


function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {

    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}

So one way of looking at them, is that in order of complexity they go Provider > Factory > Service > Value ?

Thats one way to look at it, another would be to think of Factory and Service as abstractions of Provider. Someone correct me if I am wrong but Factory and Service use Provider under the hood. Which is why provide is the "Closest to the metal" version. I believe Value is a way to define constants that can then be used application wide.

javascript - AngularJS : What is a factory? - Stack Overflow

javascript angularjs angularjs-factory
Rectangle 27 252

Your issue is not really with Angular, but with Array methods. The proper way to remove a particularly item from an array is with Array.splice. Also, when using ng-repeat, you have access to the special $index property, which is the current index of the array you passed in.

The solution is actually pretty straightforward:

<a ng-click="delete($index)">Delete</a>
$scope.delete = function ( idx ) {
  var person_to_delete = $scope.persons[idx];

  API.DeletePerson({ id: person_to_delete.id }, function (success) {
    $scope.persons.splice(idx, 1);
  });
};

Careful - this index-based solution will not work if you use multiple ng-repeats of the same object in a view (e.g. Scheduled Tasks, Unscheduled Tasks, Completed Tasks all coming out of $scope.tasks) because you will have multiple items with index 2, 3, 4, etc.

Comment above, by @shacker, about multiple ng-repeats with different filtered sets of the same array, is right on. Use method below with indexOf

@AndrewKuklewicz - indexOf can be a more expensive operation; without filtering, it's completely unnecessary. But with filtering, indexOf would be the appropriate method.

I am struggling with this and had to make a minor change to the tag generation above - being - delete({{$index}}) with the {{ }} otherwise I got the string $index - BUT I have something wrong because it never calls that method. It does when I remove any mention of the index like delete() but that doesn't really help.

javascript - AngularJS How to remove an Item from scope - Stack Overfl...

javascript angularjs
Rectangle 27 251

Your issue is not really with Angular, but with Array methods. The proper way to remove a particularly item from an array is with Array.splice. Also, when using ng-repeat, you have access to the special $index property, which is the current index of the array you passed in.

The solution is actually pretty straightforward:

<a ng-click="delete($index)">Delete</a>
$scope.delete = function ( idx ) {
  var person_to_delete = $scope.persons[idx];

  API.DeletePerson({ id: person_to_delete.id }, function (success) {
    $scope.persons.splice(idx, 1);
  });
};

Careful - this index-based solution will not work if you use multiple ng-repeats of the same object in a view (e.g. Scheduled Tasks, Unscheduled Tasks, Completed Tasks all coming out of $scope.tasks) because you will have multiple items with index 2, 3, 4, etc.

Comment above, by @shacker, about multiple ng-repeats with different filtered sets of the same array, is right on. Use method below with indexOf

@AndrewKuklewicz - indexOf can be a more expensive operation; without filtering, it's completely unnecessary. But with filtering, indexOf would be the appropriate method.

I am struggling with this and had to make a minor change to the tag generation above - being - delete({{$index}}) with the {{ }} otherwise I got the string $index - BUT I have something wrong because it never calls that method. It does when I remove any mention of the index like delete() but that doesn't really help.

javascript - AngularJS How to remove an Item from scope - Stack Overfl...

javascript angularjs
Rectangle 27 303

If you are not using ng-bind, instead something like this:

<div>
  Hello, {{user.name}}
</div>

you might see the actual Hello, {{user.name}} for a second before user.name is resolved (before the data is loaded)

<div>
  Hello, <span ng-bind="user.name"></span>
</div>

if that's an issue for you.

ng-cloak

Based on what you are saying, there no performance hit if we use {{}}? I was told, if you use {{}}, everytime, that will get inerpolate and generate the result even if the model does not change.

And how to use ng-bind if I don't want to wrap user.name inside span tag? If I uset curly brackets I'll get clean name, without html tags

@KevinMeredith it appears like that when the HTML has loaded, but angular has not (yet). Remember that it's client-side templating we're talking about. All the interpolation has to be done in the browser loading the app. Usually angular loads fast enough for it not to be noticeable, but in some cases it becomes a problem. So, ng-cloak was invented to mend this problem.

for me, this is not the answer to the question, why ngBind is better. It's just how to use ngBind instead of the {{}} annotation and a reference to ngCloak.

@Victor there is also ng-bind-template where you can combine both approaches: ng-bind-template="Hello, {{user.name}}" Here the binding still offers the performance boost and does not introduce any further nesting

javascript - AngularJS : Why ng-bind is better than {{}} in angular? -...

javascript angularjs ng-bind
Rectangle 27 300

If you are not using ng-bind, instead something like this:

<div>
  Hello, {{user.name}}
</div>

you might see the actual Hello, {{user.name}} for a second before user.name is resolved (before the data is loaded)

<div>
  Hello, <span ng-bind="user.name"></span>
</div>

if that's an issue for you.

ng-cloak

Based on what you are saying, there no performance hit if we use {{}}? I was told, if you use {{}}, everytime, that will get inerpolate and generate the result even if the model does not change.

And how to use ng-bind if I don't want to wrap user.name inside span tag? If I uset curly brackets I'll get clean name, without html tags

@KevinMeredith it appears like that when the HTML has loaded, but angular has not (yet). Remember that it's client-side templating we're talking about. All the interpolation has to be done in the browser loading the app. Usually angular loads fast enough for it not to be noticeable, but in some cases it becomes a problem. So, ng-cloak was invented to mend this problem.

for me, this is not the answer to the question, why ngBind is better. It's just how to use ngBind instead of the {{}} annotation and a reference to ngCloak.

@Victor there is also ng-bind-template where you can combine both approaches: ng-bind-template="Hello, {{user.name}}" Here the binding still offers the performance boost and does not introduce any further nesting

javascript - AngularJS : Why ng-bind is better than {{}} in angular? -...

javascript angularjs ng-bind
Rectangle 27 300

If you are not using ng-bind, instead something like this:

<div>
  Hello, {{user.name}}
</div>

you might see the actual Hello, {{user.name}} for a second before user.name is resolved (before the data is loaded)

<div>
  Hello, <span ng-bind="user.name"></span>
</div>

if that's an issue for you.

ng-cloak

Based on what you are saying, there no performance hit if we use {{}}? I was told, if you use {{}}, everytime, that will get inerpolate and generate the result even if the model does not change.

And how to use ng-bind if I don't want to wrap user.name inside span tag? If I uset curly brackets I'll get clean name, without html tags

@KevinMeredith it appears like that when the HTML has loaded, but angular has not (yet). Remember that it's client-side templating we're talking about. All the interpolation has to be done in the browser loading the app. Usually angular loads fast enough for it not to be noticeable, but in some cases it becomes a problem. So, ng-cloak was invented to mend this problem.

for me, this is not the answer to the question, why ngBind is better. It's just how to use ngBind instead of the {{}} annotation and a reference to ngCloak.

@Victor there is also ng-bind-template where you can combine both approaches: ng-bind-template="Hello, {{user.name}}" Here the binding still offers the performance boost and does not introduce any further nesting

javascript - AngularJS : Why ng-bind is better than {{}} in angular? -...

javascript angularjs ng-bind
Rectangle 27 297

In order to switch between different views, you could directly change the window.location (using the $location service!) in index.html file

<div ng-controller="Cntrl">
        <div ng-click="changeView('edit')">
            edit
        </div>
        <div ng-click="changeView('preview')">
            preview
        </div>
</div>
function Cntrl ($scope,$location) {
        $scope.changeView = function(view){
            $location.path(view); // path not hash
        }
    }

and configure the router to switch to different partials based on the location ( as shown here https://github.com/angular/angular-seed/blob/master/app/app.js ). This would have the benefit of history as well as using ng-view.

I'm getting an error that says hash is not function of $location.

I don't see hash as being part of the $location object, but there is a $$hash variable so is that it and if so it doesn't work.

@The_Brink Thank you for the edit. I dont know why it was rejected. I made changes to reflect what I was attempting to say.

The best thing to do actually is just make a normal link. <a href="/edit">Edit</a> Angular will take make sure that the click does not create a page reload. This behavior can be modified so that it triggers a reload if that is desired.

javascript - AngularJS : How do I switch views from a controller funct...

javascript angularjs ngroute