ran*_*ame 5 javascript angularjs
我一直在阅读一些文章,并没有找到解决我的问题的例子.
我的理解是:
ng-if并ng-repeat创建隔离范围.$parent.someProperty很糟糕.$parent.$parent.someProperty将是一种憎恶.因此,使用给定的模板标记,如何正确绑定控制器以使控制器属性更新?
标记:(
注意嵌套,ng-if并ng-repeat创建一种$parent.$parent情况)
<div ng-app="MyApp" ng-controller="MyCtrl">
<div ng-if="showOnCondition">
<label ng-repeat="item in repeatingItems">
{{item}}
<setting item="item" />
</label>
</div>
{{checkSetting()}}
</div>
Run Code Online (Sandbox Code Playgroud)
JavaScript的
var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.settings = {
someProperty: '',
anotherProperty: 'Hello'
}
$scope.repeatingItems = [
'One',
'Two',
'Three'
];
$scope.showOnCondition = true;
$scope.checkSetting = function() {
// When calling checkSettings(), I would like to access the value of someProperty here
return $scope.settings;
}
});
myApp.directive('setting', function() {
return {
restrict: 'E',
require: '^myCtrl',
// HOW DO I SOLVE THIS?
// $parent.$parent is bad.
template: '<input type="radio" ng-model="$parent.$parent.settings.someProperty" name="mySetting" value="{{item}}" />',
scope: {
settings: '=',
item: '='
}
};
});
Run Code Online (Sandbox Code Playgroud)
鉴于上面的例子,如何正确构造指令和/或标记以便settings.someProperty在控制器中访问?或者我需要做些什么完全不同的事情?
澄清
对于我正在尝试做的事情似乎有些混乱.该someProperty是在指令中可用的-这是工作的罚款.请注意,我试图将值分配到控制器的someProperty物业内的指令(用NG-模型)
更新
我已将上面的代码修改为已知的工作代码,并添加了一个jsFiddle.请注意它可以工作,但它$parent.$parent在模板中使用.这是我需要了解如何解决的问题.
您可以将设置传递给指令,我认为这是最简单/最直接/最干净的方法。
Angular 正确地评估settings为MyCtrl.settings,然后将其传递到指令的隔离范围setting。在指令内部,您可以在 上进行双向绑定settings,因此您可以从那里更新设置。
修改您的示例,传入标记settings中的指令:
<setting settings="settings" item="item" />
然后在JavaScript中,将其替换为模板:
template: '<input type="radio" ng-model="settings.someProperty" ng-value="item" name="mySetting" />',
这是一个工作小提琴。
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |