1

I have a simple widget I'm building that has multiple panes. I'm trying to switch between them by way of font-awesome icons along the top. My $scope has a model selected that I'd like to update when people click one of the icons.

I have been able to accomplish this by invoking a method off of the $scope, like so:

<i ng-repeat="cat in widget.data"
   ng-click="updateSelected(cat.type)">
</i>

and in my controller:

$scope.updateSelected = function (type) { $scope.selected = type; };

However, I'd like to do it more directly by updating the selected model directly in the ng-click attribute, like so:

<i ng-repeat="cat in widget.data"
   ng-click="selected=cat.type">
</i>

I've not been able to get this to work so now I'm wondering -- are you supposed to be able to directly update a model in this fashion? Or do I always need to write a handler function?

cmw
  • 855
  • 7
  • 17
  • 2
    ng-repeat creates a new scope, so when you do `ng-click="selected=cat.type"` it actually works, but it sets the selected variable of the local scope, you can try by using `ng-click="$parent.selected=cat.type"`, or with a function, which seems to be the best solution – DotDotDot Aug 23 '13 at 23:39
  • Thanks @DotDotDot, that worked. It makes sense too, but it makes me wonder why you don't have to call the function by way of `ng-click="$parent.updateSelected(cat.type)"`, since the fn shared the same scope as `selected`. – cmw Aug 23 '13 at 23:56
  • 2
    @cmw, you don't need `$parent` with a function because of the way JavaScript prototypal inheritance works: if the function is not found on the local scope, it looks up the prototype chain and finds it on the parent. Another option is to use an object in your parent (e.g., `object.selected`), rather than a primitive, then you could write `ng-click="obj.selected=cat.type"`. This is all explained in much more detail [here](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482). – Mark Rajcok Aug 24 '13 at 00:15
  • Great link @MarkRajcok, I will have to review how javascript handles inheritance, and how Angular exploits it, as this was somewhat unexpected. – cmw Aug 24 '13 at 00:31

0 Answers0