Say I write an app like this:
<script>
myArray=<?php echo $array;?>;
app={
myArray:myArray,
myIndex:myArray.length-1,
back:function(){this.myIndex--;console.log("You clicked back");},
forward:function(){this.myIndex++}
}
</script>
Now I want to add a UI so I decide to use angularJS. So I write this:
<div ng-app="myApp">
<div ng-controller="AppCtrl">
<div ng-repeat="value in myArray | slice:myIndex:myIndex+1">
<div ng-cick="back()">Back</div>
<div ng-bind="value"></div>
<div ng-cick="forward()">Forward</div>
</div>
</div>
</div>
Also I got this
var myApp=angular.module('myApp', [])
myApp.filter('slice', function() {
return function(arr, start, end) {
return arr.slice(start, end);
};
});
myApp.controller("AppCtrl",function($scope){
$.extend($scope,app);
})
Then I click the back button, and the console logs "You clicked back", but the value does not change. Why doesn't JQuery extend work in this situation and how can I get this to work correctly?
$.extend
will work fine.. But.. You don't really need it.. read/watch this.
To fix your problem... just do this:
myApp.controller("AppCtrl",function($scope){
$scope.app = app;
})
and.
<div ng-controller="AppCtrl">
<div ng-repeat="value in app.myArray | slice:app.myIndex:app.myIndex+1">
<button ng-click="app.back()">Back</button>
<div>{{value}}</div>
<button ng-click="app.forward()">Forward</button>
</div>
</div>
Hope that points you in the right direction.
update
One solution would be to use the controller as syntax... so
myApp.controller("AppCtrl",function(){
angular.extend(this,app);
})
and
<div ng-controller="AppCtrl as app">
<div ng-repeat="value in app.myArray | slice:app.myIndex:app.myIndex+1">
<button ng-click="app.back()">Back</button>
<div ng-bind="value"></div>
<button ng-click="app.forward()">Forward</button>
</div>
</div>
In the first example $scope.app
has context (because its the owner of forward,back etc that you mixed in).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With