angularjs: 范围值未在视图中更新

angularjs: scope value doesn't get updated in view

detail.html 文件中有按钮:

<div ng-controller="test.views.detail">
<div data-ng-repeat="item in details"  scroll>
    <button ng-click="showDetails(item)">The details</button>

在 detail.js 文件中

angular.module('test')
.controller('test.views.detail', function($scope) {

    $scope.detailsClicked = false;

    $scope.showDetails = function(item){
        $scope.detailsClicked = true;
    }....

在formDetail.html代码中:

<div ng-controller="test.views.detail">
{{detailsClicked}}
<div ng-if="detailsClicked">...

最初它显示 false for detailsClicked,当我点击按钮时它会转到 showDetails 函数,但 $scope.detailsClicked 的值永远不会更新!很直接不知道为什么它不起作用:(

这是因为您在两个地方使用同一个控制器,并期望作用域对象相同,但事实并非如此。每次您在标记中调用 ng-controller 时,都会创建一个新的范围对象。如果您希望它们基于相同的数据,请使用服务。

Here is an example

app.controller('test.views.detail', function($scope, detailsClicked) {

    $scope.detailsClicked = detailsClicked;

    $scope.showDetails = function(item){
        $scope.detailsClicked.isClicked = true;
    }
});

创建一个将保留数据的factory/service,确保数据是

app.factory('detailsClicked', function(){
  var data = {
    isClicked: false
  }

  return data;
});