gpt4 book ai didi

javascript - AngularJS:从布局更新 View 内容

转载 作者:行者123 更新时间:2023-12-03 09:21:57 25 4
gpt4 key购买 nike

您可以在下图中看到我正在尝试执行的操作。

enter image description here

页面上主要有两个部分。标题部分包含一个通用菜单和一个搜索文本框。

当用户单击菜单(例如“电影”)时,Movies.html View 将加载到标有 ng-view 的部分中。

每个 View 都有自己的 Controller ,定义如下:

$routeProvider
.when("/", { templateUrl: "app/albums.html", controller: "albumController" })
.when("/games", { templateUrl: "app/games.html", controller: "gamesController" })...etc

到目前为止一切顺利。这个想法是,当用户在文本框中搜索某些内容时,当前 View 将被更新。

我可以有一个 commonController 来包装 searchTextbox HTML,但是...如何从该 Controller 更新当前加载 View 的 $scope?

实现这一目标的最佳方法是什么?

谢谢大家

最佳答案

我认为你应该使用service为此。

您的commonController将通知此服务:

commonController.$inject = ['NotifyViewFactory'];
function commonController(NotifyViewFactory){
var vm = this;
vm.inputModel = '';

this.notifyService = function(){
NotifyViewFactory.setValue(vm.inputModel);
};

//may be in your example better to listen when route changed:
//and then use service
$scope.$on('$routeChangeSuccess', function(scope, next, current){
NotifyViewFactory.setValue(vm.inputModel);
});
}

工厂看起来像这样:

NotifyViewFactory.$inject = ['$rootScope'];
function NotifyViewFactory($rootScope){
return {
setValue: setValue
};

function setValue(data){
//do something with data if necessary
$rootScope.$emit('inputUpdated', data);
}
}

和 View Controller :

viewController.$inject = ['$rootScope', '$scope'];
function viewController($rootScope, $scope){
$rootScope.$on('inputUpdated',function(event, data){
$scope.someValue = data.someValue;
});
}

因此,来自 commonController 的数据可以无需任何更改地传递到 viewController,或者如果您需要一些更改 - 您可以在 setValue 中执行此操作NotifyViewFactory 的 em> 方法(在 $rootScope.$emit 调用之前)。

关于javascript - AngularJS:从布局更新 View 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31814766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com