1

I'm putting two expressions in an Angular ngClick directive. Why would $scope.refresh not = Date.now()? Does it only do certain kinds of expressions?

data-ng-click="$scope.visible = !$scope.visible; $scope.refresh = Date.now()"

This isn't a question on how to execute multiple expressions-- it's the issue that only certain expressions will be evaluated.

MatBee
  • 284
  • 6
  • 16
  • why not pass this to a function that does this logic instead of doing it inline? – ajmajmajma Jul 13 '15 at 14:12
  • possible duplicate of [How to add many functions in ONE ng-click?](http://stackoverflow.com/questions/16813945/how-to-add-many-functions-in-one-ng-click) – michelem Jul 13 '15 at 14:12
  • Doing Js functionality in html is not a recommended way – Gopinath Shiva Jul 13 '15 at 14:12
  • I chose to inline the logic because it's a piece of example code to be copied and pasted in our code style guide. It's something I ran into and was unaware that it wouldn't be able to be evaluated. – MatBee Jul 13 '15 at 14:19

3 Answers3

3

You don't have to refer $scope inside the view. I suggest to do this operation in a function:

data-ng-click="onClick()"

and inside the controller:

$scope.onClick = function(){
    $scope.visible = !$scope.visible; 
    $scope.refresh = Date.now();
}
Gopinath Shiva
  • 3,822
  • 5
  • 25
  • 48
BAD_SEED
  • 4,840
  • 11
  • 53
  • 110
  • I chose to inline the logic because it's a piece of example code to be copied and pasted in our code style guide. It's something I ran into and was unaware that it wouldn't be able to be evaluated. I want to avoid having to add that function to every Controller that uses the code. – MatBee Jul 13 '15 at 15:30
  • There are smart way to do the same thing in each controller without manually copy/paste it ;) – BAD_SEED Jul 13 '15 at 15:31
  • Yeah, I suppose I could just make a directive do it. – MatBee Jul 13 '15 at 15:32
  • I don't think you should watch inside the directive stuff, maybe better controller inheritance but i'm not an expert. google around and good luck! – BAD_SEED Jul 13 '15 at 15:33
1

I believe that you cannot use Date in an angular expression.

You should either create a function on your scope/controller to handle the click event, or create a function that returns the current time and use that instead of Date.now().

David Thibault
  • 8,638
  • 3
  • 37
  • 51
  • I haven't been able to find any documentation to show that Date wouldn't work. I'll try this and get back to you! – MatBee Jul 13 '15 at 14:22
  • 1
    [Here's a document that lists the allowed expressions](http://teropa.info/blog/2014/03/23/angularjs-expressions-cheatsheet.html) – MatBee Jul 13 '15 at 16:06
0

You have not to call $scope in html binding, you need only the property name:

HTML:

data-ng-click="visible = !visible; refresh = Date.now()"

JS Controller:

.controller('myCtrl', function ($scope) {
    $scope.visible = true;
    $scope.refresh = '';
});
michelem
  • 14,430
  • 5
  • 50
  • 66