John Papa의 줄에 style guide과 일치 함 ControllerAs 구문을 사용하도록 지시문을 업데이트했습니다. 그러나이 작업을 수행 한 후 지시문이 바인딩 된 변수가 변경되면 내 지시문이 업데이트되지 않습니다. mainCtrl.rules가 업데이트 될 때양방향 바인딩이 지시문 컨트롤러를 업데이트하지 않는 이유
이 ctrl.rules의 값이이 문제를 해결하기 위해
을 업데이트되지 않습니다 즉, 나는 ctrl.rules 변수를 업데이트하는 링크 기능의 시계를 만들했을 때 $ scope.rules 변경.이유 - 지시문과 컨트롤러가 같은 범위에 있지 않은 이유는 무엇입니까?
HTML
<div my-directive rules="mainCtrl.rules"></div>
JS - 홈페이지 Ctrl 키
rulesService.get().then(mainCtrl.rules = response.rules;);
JS - 지침
(function() {
angular.module('myModule')
.directive('myDirective', myDirective);
myDirective.$inject = [];
function myDirective()
{
var directive = {
restrict: 'A',
scope: {
rules: '='
},
controller: 'myCtrl',
controllerAs: 'ctrl',
templateUrl: "/Template/myDirective",
transclude: true,
link: linkFunc
};
return directive;
};
angular.module('myModule')
.controller('myCtrl', myCtrl);
myCtrl.$inject = ['$scope'];
function myCtrl($scope)
{
var ctrl = this;
ctrl.rules = $scope.rules;
ctrl.showRules = false;
ctrl.toggleShowRules = toggleShowRules;
function toggleShowRules() {
ctrl.showRules = !ctrl.showRules;
};
};
function linkFunc($scope, $element, $attrs, ctrl)
{
//watch the rules collection on the directive and update controller if it changes
$scope.$watch("rules", function (newValue, oldValue) {
if(newValue != oldValue)
{
ctrl.rules = newValue;
}
});
};
})();
템플릿
<div class="rules" ng-show="rules.length > 0">
<ul ng-show="ctrl.showRules">
<li ng-repeat="rule in ctrl.rules" class="rule-details">
<p>{{rule.title}}</p>
</li>
</ul>
</div>
투표를 거치려면 적어도 이유에 대해 의견을주십시오. 건설적인 피드백 부탁드립니다. – Kildareflare
'controllerAs'는 컨트롤러에 이름을 부여하여 템플릿에서 액세스 할 수 있도록하기위한 것입니다. 그래서 당신이 그것을 사용하는 방식은 올바르지 않습니다. –
이 사실을 보여주기 위해 업데이트되었습니다. – Kildareflare