0

I have been start learning AngularJS 1.4.7 and I can't understand completely the $scope variables. Is this a variable inside a Angular controller "like" public variables inside a PHP class?

For example:

I have 2 functions function1(), function2() in HomeCtrl.js and a $scope.img = null; variable, and 2 ng-click event in template file to call these functions.

On ng-cick event i call the function1 and set the value of $scope.url to somethig

Thereafter i call the function2 and console.log($.scope.url) it retutn null. Null is the initialized value of this varaiable.

I'v just set the value of $scope.url in function1 and inside function2 value of variabel is null, why?

I have no idea why happening this.

3
  • Could you provide a fiddle? Commented Nov 19, 2015 at 7:57
  • 1
    Maybe you should share the code you have so we have an example to discuss instead of assuming a lot of things. It could be due the fact you have instantiated two different HomeControllers, both having their own url variables. Commented Nov 19, 2015 at 8:46
  • Yes you'r right. I had 2 differente controller with $scope.url variabel used in same template. Thank you :) Commented Nov 19, 2015 at 11:01

2 Answers 2

1

scope is instance of controller.

When you declare a controller , scope will be avaiable there.

You can access scope through out that controller.

That's why when you change on place in a controller , change will be reflect everywhere in that scope.

Sign up to request clarification or add additional context in comments.

1 Comment

@NagyErvin you are welcome . does this solved your issue ?
0

Do you literally call $.scope.url? Then that's a problem, it should be $scope.url, no dot between "$" and "scope".

Scope variables have nothing to do with variables accessibility concept (public/private/protected/etc).

They are those "magic" variables, which can be placed inside templates using expressions, which allows data-binding in Angular, i.e., your html with that "magic" scope variables, gets automatically updated by angular, when you just change their values inside your controller, like in that callback function for ng-click. (Actually it's not that easy, here we come to $watch and $digest, but if you are not writing your custom directives, and not mixing, for example, jQuery code with Angular code, you may not think about it for now).

Two-side data-binding, automatic html updates - that's the main point of $scope and $scope variables.

Scope is not and instance of a controller, they are different Angular entities.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.