在 angular 中是否可以将 $scope 属性 移动到控制器范围?
In angular is it possible to move a $scope property to controller scope?
我现在正在创建一个嵌套控制器,父控制器传入一个变量,如下所示:
app.directive('entity', function() {
return {
restrict: 'E',
controller: 'EntityShowController',
templateUrl: '/show.html',
controllerAs: 'showCtrl',
scope: {
entity: '=' // two way binding parent/child
}
};
})
在模板中我有:
<entity entity="parent.getSelected()"></entity>
现在在子控制器中我可以这样做:
app.controller('EntityShowController', function($scope) {
// this is what I should do to access the passed in two-way sync entity
console.log($scope.entity);
// this is what I like to achieve
this.entity = $scope.entity;
$scope.entity=null;
}]);
是否可以设置控制器本地数据(this
属性)来跟踪父控制器数据($scope
属性)?
我知道我可以实施 setEntity
方法(例如)与 ng-click
相结合,但这并不是我想要实现的目标。
如果您使用的是 angular 的 1.3.x 版本,您可以在指令设置上设置 bindToController
标志,将 2 向绑定范围属性绑定到控制器实例,如果您低于 1.3.x 此选项不可用,您需要直接在作用域上工作,或者您需要建立同步机制以在控制器实例和作用域 属性 之间同步。
.directive('entity', function() {
return {
restrict: 'E',
controller: 'EntityShowController',
templateUrl: '/show.html',
controllerAs: 'showCtrl',
bindToController:true,
scope: {
entity: '=' // two way binding parent/child
}
};
})
我现在正在创建一个嵌套控制器,父控制器传入一个变量,如下所示:
app.directive('entity', function() {
return {
restrict: 'E',
controller: 'EntityShowController',
templateUrl: '/show.html',
controllerAs: 'showCtrl',
scope: {
entity: '=' // two way binding parent/child
}
};
})
在模板中我有:
<entity entity="parent.getSelected()"></entity>
现在在子控制器中我可以这样做:
app.controller('EntityShowController', function($scope) {
// this is what I should do to access the passed in two-way sync entity
console.log($scope.entity);
// this is what I like to achieve
this.entity = $scope.entity;
$scope.entity=null;
}]);
是否可以设置控制器本地数据(this
属性)来跟踪父控制器数据($scope
属性)?
我知道我可以实施 setEntity
方法(例如)与 ng-click
相结合,但这并不是我想要实现的目标。
如果您使用的是 angular 的 1.3.x 版本,您可以在指令设置上设置 bindToController
标志,将 2 向绑定范围属性绑定到控制器实例,如果您低于 1.3.x 此选项不可用,您需要直接在作用域上工作,或者您需要建立同步机制以在控制器实例和作用域 属性 之间同步。
.directive('entity', function() {
return {
restrict: 'E',
controller: 'EntityShowController',
templateUrl: '/show.html',
controllerAs: 'showCtrl',
bindToController:true,
scope: {
entity: '=' // two way binding parent/child
}
};
})