[英]Can I make scope extend an object in angularjs?
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. 现在,我想添加一个UI,因此决定使用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? 为什么在这种情况下JQuery无法扩展工作,我如何才能使其正常工作?
$.extend
will work fine.. But.. You don't really need it.. read/watch this . $.extend
可以正常工作..但是..您实际上并不需要它..阅读/观看此内容 。
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). 在第一个示例中, $scope.app
具有上下文(因为您混入了其中的forward,back等所有者)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.