AngularJS watches expression

Say we have this expression

$scope.showButton = users.is_admin() && !document.is_provided;

And then in the same controller you have a button that updates the value Document.is_provided:

<button ng-click="document.is_provided = true;">Provide document</button>

The problem is that $scope.showButtonit should now change, but it does not change.

Updated: Plnkr shows a simplified problem: http://plnkr.co/edit/Qk2jnHAmqsrNXSAjDYEk?p=preview

+4
source share
4 answers

I would like to add an answer to squiroid and explain to you why it works. I will give you a very easy way to understand, since this was a very common problem for me when I started.

Angular -, . , , , A B (, ng-), ( ). , angular ( , $, $timeout ..),

, , A, $scope B, C. , C A, ? , C, B , A . . , , . , C, , A.

, $watch ( $), . , , C, , , A, .

$scope.showButton document.is_provided. angular, document.is_provided. , , , $scope.showButton. showButton .

, , , : http://jsbin.com/vojoso/edit?js,console,output

. , . $watch , . , , .

, :)

+4

, : -

$scope.$watch(function(){
    return Users.is_admin() && !Document.is_provided;
},fuction(newVal){
$scope.showButton =newVal;
});

, :)

+3

$scope. $watch, , .

, Document REST.

UPD: , . , . $scope , data angular

, .

UPD 2: , plunker

index.html

<html ng-app="plunker">
  <body ng-controller="MainController as main">

    <div ng-show="main.data.document.is_provided">visible</div>
    <button ng-click="main.hide()">Hide</button>

    <script data-require="angular.js@1.4.x" 
            src="https://code.angularjs.org/1.4.1/angular.js" 
            data-semver="1.4.1"></script>
    <script src="app.js"></script>
  </body>
</html>

app.js

angular
  .module('plunker', [])
  .controller('MainController', MainController);

function MainController() {
    var main = this;

    this.data = {
      document: {
        is_provided: true
      }
    };

    this.hide = hide;

    function hide() {
      main.data.document.is_provided = false;
    }
}

ng-click, . ng-if ng-show.

+2

(imho) : {{ anyObject | json }} !

, , , , . | json accolades {}, , . , .

:    <body ng-controller="MainCtrl as mainCtrl">

html :

DATA: {{mainCtrl | json}}

, ! , .

:

app.controller('MainCtrl', function($scope) {

var main = this;

this.data = {
  document: {
    is_provided: true
  }
};



$scope.hide = function() {
  console.log(main);
  main.data.document.is_provided = !main.data.document.is_provided;
}
});

:   <button ng-click="hide()">Hide</button> ( )

+2

All Articles